阶高阶函数:用下划线问题(_)[重复]

问题描述 投票:1回答:1

这个问题已经在这里有一个答案:

有人能告诉我在我的代码函数序列的2和实现之间的差异。

我使用的IntelliJ IDEA与SBT。

  def traverse[A, B](a : List[A]) (f : A => Option[B]) : Option[List[B]] = {
    a.foldRight(Some(List[B]()) : Option[List[B]])(
      (x, y) => for {
        xx <- f(x)
        yy <- y
      } yield xx +: yy
    )
  }
  def sequence[A](a: List[Option[A]]): Option[List[A]] = {
    traverse(a)(x => x) //worked
    //traverse(a)(_) //Expression of type (Option[A] => Option[B_]) => Option[List[Nothing]] doesn't conform to expected type Option[List[A]]
  }

我期待最终的线来达到同样的,相反,它表明我返回一个选项[列表[没什么]。

scala
1个回答
2
投票

TL; DR,f(_)不等于f(x => x)

作为该相关SO answer雄辩地说明,你看“短表”为anonymous functionpartially applied function之间的差异。

_是表示一个参数表达式的一部分:

f(_ + 1)  // f(x => x + 1)
g(2 * _)  // g(x => 2 * x)

_本身就是一个参数:

f(_)      // x => f(x)
g(1, _)   // x => g(1, x)
h(0)(_)   // x => h(0)(x)
© www.soinside.com 2019 - 2024. All rights reserved.