【发布时间】:2019-02-19 18:07:37
【问题描述】:
在下面来自“functional-programming-in-scala”的代码中,_ 是什么意思?我认为它代表了 sequence(t) 的结果,但是当我用 sequence(t) 替换它时,它给出了我一个编译错误。为什么会这样?我该怎么做才能使这个 _ 显式?
编辑:我很困惑这个 _ 是否应该扩展为序列(t)的结果,列出下划线 here 的所有用例在这里没有帮助,我已经查看了它。
@ def sequence[A](a: List[Option[A]]): Option[List[A]] =
a match {
case Nil => Some(Nil)
case h :: t => h flatMap (hh => sequence(t) map (hh :: _))
}
defined function sequence
@
@ sequence(List(Some(1), Some(2))
)
res1: Option[List[Int]] = Some(List(1, 2))
将_ 替换为序列(t)
def sequence[A](a: List[Option[A]]): Option[List[A]] =
a match {
case Nil => Some(Nil)
case h :: t => h flatMap (hh => sequence(t) map (hh :: sequence(t)))
}
cmd4.sc:4: value :: is not a member of Option[List[A]]
case h :: t => h flatMap (hh => sequence(t) map (hh :: sequence(t)))
^
Compilation Failed
【问题讨论】:
-
我在问这个问题之前已经看到了。它没有帮助。我想知道的是它在这种情况下具体是如何工作的。它不应该是重复的
标签: scala lambda syntactic-sugar