Cha*_*kar 5 functional-programming scala purely-functional
我正在 coursera 上学习 martin odersky 的 scala 函数式编程课程。
但是,我无法理解第二个作业 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)
Run Code Online (Sandbox Code Playgroud)
问题在上面的函数中 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)
Run Code Online (Sandbox Code Playgroud)
同样的问题也适用于相交函数。
请任何人解释一下上面两个函数的操作,即这两个语句
(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)
Run Code Online (Sandbox Code Playgroud)
让我们把它分解成小块。
def union()我正在定义一个我将调用的方法union。(s: Set, t: Set)该方法将采用 2 个参数,我将其称为s和t,两者的类型均为Set。: Set该方法将返回一个类型的值Set。等等...a是什么Set?type Set = Int => Boolean啊,好吧,Set是一个以 anInt作为参数并返回 aBoolean作为结果的函数。知道了。回到union()方法。(e: Int) => s(e) || t(e)这是一个采用单个 类型参数的函数Int。我将调用该参数e。当此函数接收到 an 时,Int它将被馈送到s和t。s和t都是 type Set,这意味着当输入 a 时,Int它们返回 a Boolean。那么我们将有 2 个Boolean值,它们将被进行“或”运算以生成一个与( in, out)Boolean的定义匹配的单个值,这样我们就完成了。SetIntBoolean现在让我们创建一个示例,看看如何使用它。
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
Run Code Online (Sandbox Code Playgroud)
e称为参数。参数绑定到参数当函数应用于参数时,
例如,在函数中
\n\nval f: Int \xe2\x87\x92 Int = i \xe2\x87\x92 i + 1\nRun Code Online (Sandbox Code Playgroud)\n\ni是一个参数。如果将 引用的函数应用于f参数,例如 ,2则在函数内部,i绑定到参数的值,即在函数内部,取消引用的i计算结果为2。因此,应用引用的函数f将计算为3:
f(2)\n//=> 3\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2709 次 |
| 最近记录: |