Scala 函数 => 作为参数

标签 scala

任何人都可以向我解释为什么以下

  /**
   * 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/

相关文章:

mysql - Scala 和 MySQL JDBC 驱动程序

scala - 在 Scala 中连接两个长度不等的列表

scala - Akka:当你告诉 ActorRef 并且它希望你问时会发生什么?

scala - Play scala 集成规范 - 通过 Guice 注入(inject)依赖项

scala - 在 Scala 中使用闭包

scala - 等于 scala 中的自由函数定义

Scala 密封特征 - 复制枚举 `withName` 方法

scala - 类型参数中 `::` 的含义?

scalaz 7 相当于来自 scalaz 6 的 `<|*|>`

scala - scala.collection.TraversableView.NoBuilder 是如何工作的?