2013-10-08 56 views
2
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 = 
    // ???? 

這就是我給的目前爲止。我對如何實現這種方法有些困惑。我會調用該方法,像這樣:檢查2套列入斯卡拉

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

我不知道這是否會工作,但似乎太簡單了:

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

只是在尋找一些指導。謝謝。

+0

實際上,即使你的* simple *函數最好寫作爲def <=(other:FinSet [T]):Boolean = this == other'。顯然這不會滿足'<='的其他部分 - *如果一個集合比另一個更大*怎麼辦?例如(以大小4設置)<=(以大小5設置)應該也是真實的。你會如何檢查這個? –

+0

哦,好的我看到你的觀點,如果一套比另一套小。大小寫是否匹配?也可以說我不需要擔心尺寸差異,這種實施是否正確? – user2516663

回答

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) 
+0

我有一個包含方法已經定義,但我不能做任何其他的方法,沒有給出,所以我不能讓所有的一個 – user2516663

+0

爲什麼不呢?這是一個功課問題嗎?無論如何,你總是可以將它定義爲'<='中的內部函數,然後調用它。 – Shadowlands

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) 
+0

當我嘗試使用forall(x +。thatSet包含x)時,出現此錯誤: value forall不是FinSet的成員[T] 我明白爲什麼會出現此錯誤,那麼我該如何解決此問題。 – user2516663

+0

也許嘗試使用刪除元素的方法,後者。 –

+0

nope仍然得到相同的錯誤,除了 - 運算符 – user2516663