任何人都可以向我解释为什么以下
/**
* Returns a set transformed by applying `f` to each element of `s`.
*/
def map(s: Set, f: Int => Int): Set = x => exists(s, y => f(y) == x)
不等于
def map(s: Set, f: Int => Int): Set = x => exists(s, f(x))
其中“exists”是一个函数,它返回
s
内是否存在有界整数。 (第一个参数)满足p
(第二个论点)。为什么需要指定“y => f(y) == x”?太感谢了!
最佳答案
exists
的第二个参数的类型为 Int => Boolean
(对吗?),换句话说,它需要一个来自 Int
的函数至Boolean
.现在,f(x)
不符合该类型 - 它的类型为 Int
.所以- y => f(y) == x
创建一个具有正确类型的函数,如果其输入等于 x
,则返回 true .
如果多余的字符困扰您 - 您也可以使用匿名参数 '_' 将其缩短一点:
def map(s: Set, f: Int => Int): Set = x => exists(s, f(_) == x)
关于Scala 函数 => 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38095320/