代码直接映射到您提供的描述。
让我们举一个简单的例子来演示用法:首先有一个空集,比如说e
然后给它添加一个元素来获得另一个集合,比如s1
。然后,您将有 2套,e
和s1
:
val e = Empty
e contains 42 // will be false
// create s1 from e
val s1 = e incl 1 // e does not change; it remains a reference to the Empty set.
// Now we have s1, a set that should contain (1) and nothing else.
s1 contains 1 // will be true
s1 contains 42 // will be false
我猜你所熟悉的斯卡拉速记,可以让你键入的 s1 incl 1
代替s1.incl(1)
注意,这里不仅可以永远是一个空集,所以这是一样好:
val s1 = Empty incl 1
那么,让我们说你想添加,说2
得到另一套s2
其元素 必须包括{1, 2}
。
val s2 = s1 incl 2
s2 contains 1 // true
s2 contains 2 // true
s2 contains 3 // false
所以任意一组的方法incl
接受一个元件和返回一个新的组 - 它不 变化的集(其include
方法被称为原始对象ob)。
我们有两种类型的树集;空和非空,并且每个具有用于incl
一个实现:
// Empty
def incl(x:Int): IntSet = new NonEmpty(x, Empty, Empty)
读取:“添加元素为空(树)组产生另一组是一个非空的树只有一个根值为1
的节点和空的左右子树。“
非空集具有构造函数参数elem
,它表示树的根并且对NonEmpty
中的所有方法都可见。
// Non-Empty
def incl(x: Int): IntSet =
if (x < elem) new NonEmpty(elem, left incl x, right)
else if (x > elem) new NonEmpty(elem, left, right incl x)
else this
读取:(在上面的if-else的相反的顺序):
- 添加元素
x
到非空集,其根元素也是x
给你同一组(this
)
- 添加元素
x
到非空集,其根元件比01少 x
给你另一个集,其中:
- 根元素是一样的原来设定
- 的左子树是不变的 - 一样的,在原设定
- 的新权子树变成原来的右子树树
x
添加到它“:right incl x
- 添加元素
x
到非空集,其根元件比x
给你另一个集,其中更大:
- 根元素是相同的原始集合
- 的right子树不变 - 与原始集相同
- 新左子树成为原始左子树
x
添加到它“:left incl x
的‘持久性’是一个事实,即没有树或子树是是否会改变实现。在这个例子中
val s1 = Empty incl 1 // s1 is a tree with only a root(1) an no branches.
val s2 = s1 incl 2 // s2 is another tree with -
// - the same root(1),
// - the same left-subtree as s1, (happens to be Empty)
// - a new subtree which in turn is a tree with -
// - the root element (2)
// - no left or right brances.
s1 contains 1 // true
s1 contains 2 // false
s2 contains 1 // true
s2 contains 2 // true
val s3 = s2 incl -3 // s2.incl(-3)
// from s2 we get s3, which does not change s2's structure
// in any way.
// s3 is the new set returned by incl, whose
// - root element remains (1)
// - left subtree is a new tree that contains
// just (-3) and has empty left, right subtrees
// - right subtree is the same as s2's right subtree!
s3.contains(-3) // true; -3 is contained by s3's left subtree
s3.contains(1) // true; 1 is s3's root.
s3.contains(2) // true; 2 is contained by s3's right subtree
s3.contains(5) // false
我们只使用incl
从其它套派生集(树),在不改变原设定。这是因为在非常阶段,我们要么 -
- 回报新基于离开的人,而不是修改 现有结构,
- 回报现有的结构,因为它们的数据结构。
contains
的工作方式相同:Empty
有任何输入返回false
的实现。 NonEmpty
如果给定元素与它的根相同,或者它的左边或右边的子树都包含它,它会很快返回true!
请注意,这不是一个纯功能树。它是一棵不变的树,每个树操作都会在内存中创建一个可以保存的类实例。 – 0kcats