我已经接受了马丁·奥德斯基在课程中的scala中的函数式编程课程。 但是,我无法理解第二个Assignment 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)
问题在上面的功能是什么?它从何而来 ?我知道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)
e
被称为参数。将函数应用于参数时,参数将绑定到参数。
例如,在函数中
val f: Int ⇒ Int = i ⇒ i + 1
i
是一个参数。如果将f
引用的函数应用于参数,比如2
,那么在函数内部,i
绑定到参数的值,即在函数内部,解引用i
求值为2
。因此,应用f
引用的函数将评估为3
:
f(2)
//=> 3
def union(s: Set, t: Set): Set = (e: Int) => s(e) || t(e)
让我们把它分解成小块。
def union()
我正在定义一种方法,我称之为union
。(s: Set, t: Set)
这个方法将采用两个参数,我称之为s
和t
,两种类型都是Set
。: Set
此方法将返回typeSet
的值。等等......什么是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
in,Boolean
out)的定义匹配,所以我们已经完成了。现在让我们创建一个示例,看看如何使用它。
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
记住在这个任务中如何定义Set
:它只是一个接受Int
并返回Boolean
的函数。当你将一些Int
传递给这个函数时,如果Int
在Set
中,函数返回true,如果不是,则返回false。换句话说,这种类型的Set
实际上并不是一个集合,而是对给定Set
中某些东西的含义的定义。
现在,在两个union
s之间调用Set
怎么办?那么它产生了一个Set
,其成员至少在这两个Set
s中的一个。请记住,Set
只是一个Int => Boolean
函数,所以:
(e: Int) => s(e) || t(e)
是一个函数,它接受一些Int
参数,称之为e
,如果QITHxswpoi为真或者s(e)
为真,则返回true。根据t(e)
方法声明,什么是union
和s
?
t
def union(s: Set, t: Set):
是描述s
是否在Int
Set
中的功能;同样对于s
。因此,t
意味着s(e) || t(e)
必须在一个或两个e
s中,因为两个Set
s的union
返回true - 这正是Set
的定义。