从scala列表中获取头项和尾项 [英] Get head item and tail items from scala list
问题描述
scala中是否有一种方法来获取List或Seq的(单个)头部元素以及列表的(集合)尾部?我知道有
Is there a method in scala to get the (single) head element of a List or Seq and the (collection) tail of the list? I know there's
def splitAt(n: Int): (List[A], List[A])
,我可以轻松地从元组的第一个列表中获取单个项目.但是,有没有内置的方法基本上就是这个?
and I can easily grab the single item from the first list of the tuple. But is there any built in method that is basically this?
def splitAtHead: (Option[A], List[A])
就像我说的那样,您可以轻松地链接splitAt
以返回正确的签名,但是我发现内置的方法可能能够保存中间元组.
Like I said, you can easily chain splitAt
to return the right signature, but I figured a built in method might be able to save an intermediate tuple.
@ om-nom-nom的答案是正确的,但这就是为什么我不能使用他的第二版.
@om-nom-nom's answer is correct, but this is why I couldn't use his 2nd version.
List[S](s1, s2, s3, s4).sortBy { _.f (h) } match {
case hd :: tail => recurse(tail)
}
推荐答案
您可以使用模式匹配:
val hd::tail = List(1,2,3,4,5)
//hd: Int = 1
//tail: List[Int] = List(2, 3, 4, 5)
或者只是.head/.tail方法:
Or just .head/.tail methods:
val hd = foo.head
// hd: Int = 1
val hdOpt = foo.headOption
// hd: Option[Int] = Some(1)
val tl = foo.tail
// tl: List[Int] = List(2, 3, 4)
这篇关于从scala列表中获取头项和尾项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!