繁体   English   中英

数组匹配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) 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM