【发布时间】:2018-06-05 05:46:03
【问题描述】:
我在 coursera 上的 scala 中参加了 martin odersky 的函数式编程课程。
但是,我无法理解第二个作业 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)
【问题讨论】:
-
Set是一个函数!所以,在intersect你return 一个函数。它是一个返回函数的函数。一开始可能听起来很吓人,但它非常强大。与传递“普通”参数一样,您可以传递一个函数(此处为Set)。就像你说的“如果我有一个Int类型的e,那么intersect将返回......”
标签: scala functional-programming purely-functional