【问题标题】:meaning of scala underscore in list construct列表构造中scala下划线的含义
【发布时间】: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


【解决方案1】:

在任何情况下,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 内部还是在其他地方使用,完全无关紧要。

【讨论】:

    猜你喜欢
    • 2010-12-08
    • 2020-01-04
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 2021-07-04
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多