下面的函数生成一个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上提供的课程,
它应该产生结果
谁能告诉我怎么了?
答案 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))