use*_*318 0 functional-programming scala
我有一个非常简单的集合 s1 {1, 2} 示例,我想对其应用谓词 p > 1。现在我已经实现了这个功能,它给了我正确的结果。
def filter(s: Set, p: Int => Boolean): Set = {(i: Int) => s(i) && p(i)}
Run Code Online (Sandbox Code Playgroud)
集合的定义在哪里
type Set = Int => Boolean
Run Code Online (Sandbox Code Playgroud)
但是在 Scala 中有更优雅的方法吗?
使用本课程对 a 的定义Set,您的答案非常优雅。
由于谓词实际上也是 a Set,filter因此通过重用该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)
Run Code Online (Sandbox Code Playgroud)
因为Coursera Honor Code禁止分享作业答案,所以我忽略了 intersect 的实现。