Dav*_*cht 6 c# functional-programming set immutability
.NET BCL是否具有不可变的Set类型?我正在编写一个C#的功能方言,并希望做类似的事情
new Set.UnionWith(A).UnionWith(B).UnionWith(C)
Run Code Online (Sandbox Code Playgroud)
但我能找到的最好的是HashSet.UnionWith,这将需要以下一系列调用:
HashSet composite = new HashSet();
composite.UnionWith(A);
composite.UnionWith(B);
composite.UnionWith(C);
Run Code Online (Sandbox Code Playgroud)
这种用途高度参考不透明,使其难以优化和理解.如果没有编写自定义功能集类型,有没有更好的方法呢?
Joh*_*son 11
ImmutableStack<T>ImmutableQueue<T>ImmutableList<T>ImmutableHashSet<T>ImmutableSortedSet<T>ImmutableDictionary<K, V>ImmutableSortedDictionary<K, V>更多信息在这里
关于工会,这个测试通过:
[Test]
public void UnionTest()
{
var a = ImmutableHashSet.Create("A");
var b = ImmutableHashSet.Create("B");
var c = ImmutableHashSet.Create("C");
var d = a.Union(b).Union(c);
Assert.IsTrue(ImmutableHashSet.Create("A", "B", "C").SetEquals(d));
}
Run Code Online (Sandbox Code Playgroud)
更新
这个答案是在不久前写的,从那时起,在System.Collections.Immutable命名空间中引入了一组不可变的集合.
原始答案
您可以为此推出自己的方法:
public static class HashSetExtensions {
public static HashSet<T> Union<T>(this HashSet<T> self, HashSet<T> other) {
var set = new HashSet<T>(self); // don't change the original set
set.UnionWith(other);
return set;
}
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
var composite = A.Union(B).Union(C);
Run Code Online (Sandbox Code Playgroud)
你也可以使用LINQUnion,但要获得一个集合,你需要将结果传递给HashSet构造函数:
var composite = new HashSet<string>(A.Union(B).Union(C));
Run Code Online (Sandbox Code Playgroud)
但是,HashSet它本身是可变的.您可以尝试使用F#的不可变集.
此外,正如ErikE的评论中所提到的,使用Concat产生相同的结果并且可能表现更好:
var composite = new HashSet<string>(A.Concat(B).Concat(C));
Run Code Online (Sandbox Code Playgroud)