首页 > 解决方案 > scala:附加两个列表

问题描述

我有以下 scala 代码片段:

   def append(as: List[Int], bs: List[Int]): List[Int] = as match {
      case Nil => bs
      case x::xs => x::append(xs, bs)
    }

我不明白x::该行在哪里x::append(xs, bs)。我知道当列表as为空时,bs将被返回(附加一个之前不为空的时间)。但是scala如何知道在提到的行中应该附加到asasasbsx::(..,..)

标签: scalalist

解决方案


append如果我们脱糖一点,也许会有所帮助

def append(as: List[Int], bs: List[Int]): List[Int] = 
  as match {
    case Nil => bs
    case ::(x, xs) =>
      val list = append(xs, bs)
      list.::(x)
  }

注意如何::出现两次,但是第一个在

case ::(x, xs)

实际上是一个case class,尽管它的符号名称看起来很奇怪,它的声明看起来有点像这样

case class :: (head: A, next: List[A])

而另一方面,第二::

list.::(x)

实际上是一种右关联方法Adds an element at the beginning of this list看起来像这样

def :: (elem: B): List[B]

请注意如何在正确的参数上调用x :: list等效list.::(x)而不是x.::(list)含义。::


推荐阅读