我在 coursera 上的 scala 中参加了 martin odersky 的函数式编程类(class)。
但是,我无法理解第二个作业 Funsets.scala 的解决方案。
type Set = Int => Boolean
/**
* Indicates whether a set contains a given element.
*/
def contains(s: Set, elem: Int): Boolean = s(elem)
/**
* Returns the union of the two given sets,
* the sets of all elements that are in either `s` or `t`.
*/
def union(s: Set, t: Set): Set = (e: Int) => s(e) || t(e)
问题在上面的函数中,什么是e?它从何而来 ?我知道 union 函数结合了这两个集合,但是这里我从方法定义中理解的是,它需要 2 个集合作为输入并返回结果并集,那么 e 是从哪里来的呢?
/**
* Returns the intersection of the two given sets,
* the set of all elements that are both in `s` or `t`.
*/
def intersect(s: Set, t: Set): Set = (e: Int) => s(e) && t(e)
同样的问题也适用于相交函数。
请任何人解释一下上述两个函数的操作,即这两个语句
(e: Int) => s(e) || t(e) 和 (e: Int) => s(e) && t(e)
请您参考如下方法:
def union(s: Set, t: Set): Set = (e: Int) => s(e) || t(e)
让我们把它分解成小块。
-
def union()我正在定义一个我将调用的方法union. -
(s: Set, t: Set)此方法将采用我将调用的 2 个参数s和t, 均为Set类型. -
: Set此方法将返回Set类型的值.等等……什么是Set? -
type Set = Int => Boolean啊,好的,Set是一个接受Int的函数作为参数并返回Boolean因此。知道了。返回union()方法。 -
(e: Int) => s(e) || t(e)这是一个接受Int类型的单个参数的函数。 .我将调用该参数e.当此函数收到Int它将被馈送到s和t.s和t都是类型Set,这意味着当喂食Int他们返回Boolean.那么我们将有 2 个Boolean值,它们将被或在一起以产生单个Boolean,它与Set的定义相匹配(Int输入,Boolean输出),所以我们完成了。
现在让我们创建一个示例,看看如何使用它。
val setA:Set = x => x == 5 //this Set is true only for 5
val setB:Set = y => y == 2 //this Set is true only for 2
val setU = union(setA, setB) //setA is parameter s, setB is parameter t
setU(2) //'e' is now 2, this returns true
setU(5) //'e' is now 5, this returns true
setU(25) //'e' is now 25, this returns false


