首页 > 解决方案 > 列表构造中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

标签: scalalambdasyntactic-sugar

解决方案


在每种情况下,hh :: _只是 的快捷方式_.::(hh),而后者又是x => x.::(h), 或的快捷方式x => hh :: x。在这种情况下,参数的类型是List[A](因为它是As 内的列表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还是在其他地方使用,都完全无关紧要。


推荐阅读