scala中是否有一种方法来获取List或Seq的(单个)头部元素以及列表的(集合)尾部?我知道有
def splitAt(n: Int): (List[A], List[A])
并且我可以轻松地从元组的第一个列表中获取单个项目。但是是否有基本上是这种内置方法?
def splitAtHead: (Option[A], List[A])
[就像我说的那样,您可以轻松地链接splitAt
以返回正确的签名,但是我认为内置方法可以保存中间元组。
编辑:
@@ om-nom-nom的答案是正确的,但这就是为什么我不能使用他的第二版。
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方法:
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)
tail
方法返回一个集合,该元素由除第一个元素(基本上是head
)以外的所有元素组成。
+------------------+------------------------+-------------------------------+
| Input | head | tail |
+------------------+------------------------+-------------------------------+
| List() | NoSuchElementException | UnsupportedOperationException |
| List(1) | 1 | List() |
| List(1, 2, 3, 4) | 1 | List(2, 3, 4) |
| "" | NoSuchElementException | UnsupportedOperationException |
| "A" | 'A' (char) | "" |
| "Hello" | 'H' | "ello" |
+------------------+------------------------+-------------------------------+
回答@Leandro问题:是的,我们可以做到。下面是一个示例:
scala> var a::b::c = List("123", "foo", 2020, "bar")
a: Any = 123
b: Any = foo
c: List[Any] = List(2020, bar)
scala> var a::b::c = List("123", "foo", "bar")
a: String = 123
b: String = foo
c: List[String] = List(bar)
scala> var a::b::c = List("123", "foo")
a: String = 123
b: String = foo
c: List[String] = List()