2013-10-06 51 views
0

我有一個集合s1 {1,2}的非常簡單的例子,我想對它應用一個謂詞p> 1。現在我已經實現了這個功能,它給了我正確的結果。Scala預測和過濾功能?

def filter(s: Set, p: Int => Boolean): Set = {(i: Int) => s(i) && p(i)} 

其中一套定義是

type Set = Int => Boolean 

但是,有沒有在斯卡拉做的更優雅的方式?

+0

我想你有個很好的理由像這樣定義'Set'而不是使用標準的Scala集合庫? – ghik

+0

是的,它是Martin Odersky的Coursera課程作業的一部分。 – user1343318

+0

@ user1343318你可以在'i'後面放置'{}'和類型註釋,所以它的主體看起來像這樣:'i => s(i)&& p(i)'。除此之外,它看起來很好...... :) –

回答

3

使用本課程對Set的定義,您的答案非常優雅。

由於謂詞實際上是一個Setfilter本來可以更加簡潔通過重用intersect功能:

/** 
* Returns the intersection of the two given sets, 
* the set of all elements that are both in `s` and `t`. 
*/ 
def intersect(s: Set, t: Set): Set = ??? 

/** 
* Returns the subset of `s` for which `p` holds. 
*/ 
def filter(s: Set, p: Int => Boolean): Set = intersect(s, p) 

我離開了交叉執行,因爲該Coursera Honor Code防止共享分配的答案。