数组匹配 scala 的最后一个元素

last element of array matching scala

下午好!我正在使用 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 是常量并且对所有文件都相等)列,所以我只想匹配其中的一些,而不是写类似 case Array(item1, item2 , ..., itemN) => List(item1, item2, itemK, itemN)

谢谢!

您不需要将列表转换为数组,因为列表是为模式匹配而设计的。

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))

或者 Kolmar

建议的更简洁的解决方案
scala> myList match { 
  case item :: site :: buyer :: (_ :+ date) => List(item, site, buyer, date) 
}