列表构造中scala下划线的含义
meaning of scala underscore in list construct
在“functional-programming-in-scala”中的以下代码中,_
在这里是什么意思?我认为它代表了 sequence(t) 的结果,但是当我用 sequence(t) 替换它时), 它给了我一个编译错误。这是为什么?我该怎么做才能使这个 _ 明确?
编辑:我很困惑这个 _
是否应该扩展为 sequence(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
在任何情况下,hh :: _
只是 _.::(hh)
的快捷方式,而后者又是 x => x.::(h)
或 x => hh :: x
的快捷方式。本例中的参数类型是 List[A]
(因为它是 Option
中的 A
列表)。因此,您的代码与以下代码的作用相同:
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 ((xs: List[A]) => hh :: xs))
}
它是在 flatMap
内部还是其他地方使用,完全无关紧要。
在“functional-programming-in-scala”中的以下代码中,_
在这里是什么意思?我认为它代表了 sequence(t) 的结果,但是当我用 sequence(t) 替换它时), 它给了我一个编译错误。这是为什么?我该怎么做才能使这个 _ 明确?
编辑:我很困惑这个 _
是否应该扩展为 sequence(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
在任何情况下,hh :: _
只是 _.::(hh)
的快捷方式,而后者又是 x => x.::(h)
或 x => hh :: x
的快捷方式。本例中的参数类型是 List[A]
(因为它是 Option
中的 A
列表)。因此,您的代码与以下代码的作用相同:
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 ((xs: List[A]) => hh :: xs))
}
它是在 flatMap
内部还是其他地方使用,完全无关紧要。