检查2套包含在Scala中

时间:2013-10-08 21:11:38

标签: scala set inclusion

abstract class FinSet[T] protected () {
  // given a set other, it returns true iff every element of this is an element of other
  def <=(other:FinSet[T]): Boolean = 
    // ????

这就是我到目前为止所给予的。我对如何实现此方法感到有些困惑。我会这样调用这个方法:

Set(1,2,3).<=(Set(3,2,1)) which should return true

我想知道这是否有效,但似乎太简单了:

def <=(other:FinSet[T]): Boolean = if (this == other) true else false

只是寻找一些指导。感谢。

2 个答案:

答案 0 :(得分:2)

&安培; - 表示交集,如果第二个集合没有第一个集合中的元素,则以下代码将返回false。

(thisSet & thatSet) == thisSet

详细说明此代码计算此集与另一集之间的交集,并检查this中的元素是否等于第一个表达式的结果。

see & or intersect(more verbose version) method in Scaladoc

您也可以这样做:

thisSet.forall(x => thatSet contains x)

或更简洁:

thisSet.forall(thatSet contains _)

或者像这样:

(thisSet ++ thatSet) == thatSet

或者可能是这样的:

(thatSet -- thisSet).size == (thatSet.size - thisSet.size)

答案 1 :(得分:1)

修改要求:您要检查是否为此集合的所有元素,另一个包含元素。

这听起来像是你可能想要的两个更原始的功能的组合。所以,如果你还没有这样做,我会定义方法:

def forall(predicate: T => Boolean): Boolean // Checks that predicate holds for all elements

def contains(elem: T): Boolean // Check that elem is an element of the set

然后方法<=转为:

def <=(other: FinSet[T]): Boolean = forall(other.contains)