scala - 列表构造中scala下划线的含义
问题描述
在以下代码中来自“功能编程in-scala,_
这里是什么意思?我认为它代表sequence(t)的结果,但是当我用sequence(t)替换它时,它给了我一个编译错误。为什么是吗?我该怎么做才能使这个 _ 明确?
编辑:我很困惑这是否_
应该扩展为序列(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 :: _))
}
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]
(因为它是A
s 内的列表Option
)。因此,您的代码与以下代码相同:
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
还是在其他地方使用,都完全无关紧要。
推荐阅读
- c++ - 为 opencv 模块 xfeatures2d 创建一个 .lib 文件
- python - 当用户从索引页面单击“上传”时发生了什么?
- typescript - TypeScript:有没有办法检查无限嵌套数组类型?
- java - Scrollview 不能在 android studio 上运行?
- php - PHP多维数组排序将一个元素值保留在第一个位置
- python - 有效边界看起来不太好
- javascript - 在循环中使用 Async Await
- desktop-bridge - 尝试旁加载已通过 Visual Studio 中的桌面桥的应用程序
- java - 在java中进行强制转换的原因是什么?
- php - 以不同的用户身份运行 httpd?