为什么使用函数跨度时缺少第一个元素?

时间:2018-10-25 06:02:48

标签: scala

下面的函数生成一个List

def pack[T](xs: List[T]): List[List[T]] = xs match {
  case Nil => Nil
  case x::xs =>
    val (first, rest) = xs span(y => y==x)
    first::pack(rest)
}

在列表上应用pack

val lis4 = List("a", "a", "a", "b", "c", "c", "a")

我得到一个结果

res3: List[List[String]] = List(List(a, a), List(), List(c), List())

但是,根据马丁·奥德斯基(Martin Odersky)在Coursera上提供的课程,

enter image description here

它应该产生结果

enter image description here

谁能告诉我怎么了?

1 个答案:

答案 0 :(得分:2)

您正在用模式匹配内的xs的本地绑定遮盖在方法级别定义的xs。注意,在Oderskys示例中,本地模式匹配绑定称为xs1

def pack[T](xs: List[T]): List[List[T]] = xs match {
  case Nil => Nil
  case x :: xs1 =>
    val (first, rest) = xs span(y => y == x)
    first :: pack(rest)
}

为使这一点更加清晰,您可以使用_忽略模式匹配中列表的尾部:

def pack[T](xs: List[T]): List[List[T]] = xs match {
  case Nil => Nil
  case x :: _ =>
    val (first, rest) = xs span(y => y == x)
    first :: pack(rest)
}

收益:

scala> pack(List("a", "a", "a", "b", "c", "c", "a"))
res2: List[List[String]] = List(List(a, a, a), List(b), List(c, c), List(a))