我正在尝试使用模式匹配在 Scala 中查找列表的最后一个元素。我试过以下代码
def last[A](list: List[A]):A = list match {
case head :: Nil => head
case head :: tail => last(tail)
case _ => Nil
}
最后一种情况,即 case _ => Nil
由于类型不匹配而抛出错误(发现 Nil.type 需要 A)我知道这个问题可以使用其他方法解决,但只使用模式匹配有没有办法解决这个问题?
由于列表是通用类型,所以我无法替换
Nil
类型为 A 的默认值只能在运行时确定。删除此行:
case _ => Nil
显然是有效的,但有一个警告,它会在 Nil 参数的情况下失败。那么,在这种情况下我该如何处理 Nil 参数呢?
最佳答案
使用 Option[T]
返回结果,所以如果有元素返回 Some(lastElement)
否则 Option.empty
例子,
def last[A](list: List[A]): Option[A] = list match {
case head :: Nil => Option(head)
case head :: tail => last(tail)
case _ => Option.empty
}
it("returns last element") {
assert(last(List("apple")) == Some("apple"))
assert(last(List("apple", "mango")) == Some("mango"))
assert(last(List()) == Option.empty)
assert(last(List()) == None)
}
如何访问
Option[T]
? last(List("In absentia", "deadwind")) match {
case Some(lastValue) => println(s"Yayy there was lastValue = ${lastValue}") //prints Yayy there was lastValue = deadwind
case None => println("Oops list was empty")
}
last(List()) match {
case Some(lastValue) => println(s"Yayy there was lastValue = ${lastValue}")
case None => println("Oops list was empty") //prints Oops list was empty
}
// or using map
last(List("In absentia", "deadwind")).map(lastValue => print(s"lastValue is ${lastValue}"))
关于scala - 模式匹配以查找列表的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43972000/