scala - 模式匹配以查找列表的最后一个元素

标签 scala pattern-matching

我正在尝试使用模式匹配在 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/

相关文章:

function - 为什么在函数定义中首选模式匹配?

c# - "x is null"和 "x == null"有什么区别?

c++ - 返回字符串中模式的所有非重叠匹配项

scala - 将 ActorRef 传递给其他 Actor 是好是坏?

java - 如何以特定帧速率更新 Swing Canvas ?

scala - Scala 中类型参数的默认值

f# - 模式匹配,F# 与 Erlang

c++ - 在字符串中查找所有具有最大长度的有序序列

scala - 无法在 ScalaTest 中导入 Spark 隐式

Scala如何重复Array的第一个元素直到Array.size达到一定数量