下午好!我正在使用Scala,我想匹配列表的前三个元素和最后一个元素,无论它们在列表中有多少。
val myList:List[List[Int]] = List(List(3,1,2,3,4),List(23,45,6,7,2),List(3,3,2,1,5,34,43,2),List(8,5,3,34,4,5,3,2),List(3,2,45,56))
def parse(lists: List[Int]): List[Int] = lists.toArray match{
case Array(item, site, buyer, _*, date) => List(item, site, buyer, date)}
myList.map(parse _)
但我明白了:error: bad use of _* (a sequence pattern must be the last pattern)
我理解为什么会得到它,但我怎么能避免?
我的用例是我从hdfs读取,并且每个文件都有精确的N(N对于所有文件都是常量且相等)列,所以我想只匹配其中的一些,而不写{{ {1}}
谢谢!
答案 0 :(得分:3)
您不需要将列表转换为数组,因为列表是为模式匹配而设计的。
scala> myList match {
case item :: site :: buyer :: tail if tail.nonEmpty =>
item :: site :: buyer :: List(tail.last)
}
res3: List[List[Int]] = List(List(3, 1, 2, 3, 4), List(23, 45, 6, 7, 2),
List(3, 3, 2, 1, 5, 34, 43, 2), List(3, 2, 45, 56))
建议的更简洁的解决方案
scala> myList match {
case item :: site :: buyer :: (_ :+ date) => List(item, site, buyer, date)
}