1

你知道为什么这个程序没有给出预期的答案(List(3,3))吗?

val l=List(List(1,2),List(3,3))
println(l.filter(_ match{
    case u::v => u==v
    case _ => false
}))

谢谢!

4

4 回答 4

3
case u::v => u==v

在这里,u是类型Intv而是类型List[Int]。他们不可能相等。

于 2013-09-11T13:37:18.963 回答
2

如果您可能正在处理任意长度的列表并希望仅过滤到所有元素相同的列表,则另一种编码方式将很有用,它将是:

l.filter(ls => !ls.isEmpty && ls.forall(_ == ls.head))

(该!ls.isEmpty片段假定您希望排除空列表)

于 2013-09-11T13:54:30.307 回答
2

如果要从子列表中提取前两个元素并进行比较,则需要::两个case

l.filter { 
  case u :: v :: _ => u == v
  case _ => false
}

如果要确保子列表的所有元素都相等,可以使用forall

l.filter {
  case h :: Nil => false // if you want to exclude single elements
  case h :: r => r.forall(_ == h)
  case _ => false
}
于 2013-09-11T14:00:50.630 回答
0

您需要检查类 ::的文档。它采用的构造函数参数是(hd: B, tl: List[B])

在你的情况下u成为hdvList[In]。做u==v就像做hd.equals(list)会给出错误的结果。

scala> val l= List(List(1,2),List(3,3),List(1),List(1,2,3),List(4,4,4,4))
l: List[List[Int]] = List(List(1, 2), List(3, 3))

scala> l.filter(_ match{
    case u::v =>  Some(u) == v.headOption
    case _ => false
})
res8: List[List[Int]] = List(List(3, 3), List(4, 4, 4, 4))

以上是一种惯用的做法。

于 2013-09-11T13:38:06.650 回答