你知道为什么这个程序没有给出预期的答案(List(3,3))
吗?
val l=List(List(1,2),List(3,3))
println(l.filter(_ match{
case u::v => u==v
case _ => false
}))
谢谢!
case u::v => u==v
在这里,u
是类型Int
,v
而是类型List[Int]
。他们不可能相等。
如果您可能正在处理任意长度的列表并希望仅过滤到所有元素相同的列表,则另一种编码方式将很有用,它将是:
l.filter(ls => !ls.isEmpty && ls.forall(_ == ls.head))
(该!ls.isEmpty
片段假定您希望排除空列表)
如果要从子列表中提取前两个元素并进行比较,则需要::
两个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
}
您需要检查类 ::的文档。它采用的构造函数参数是(hd: B, tl: List[B])
在你的情况下u
成为hd
和v
是List[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))
以上是一种惯用的做法。