[英]Scala: Return head of list but empty list can't return Nil
我才剛剛開始學習Scala,並且頭部功能有些麻煩。 我想從A元素列表中返回第一個元素。 但是對於Nil,我不知道該返回什么。 該函數期望A,但是由於A是抽象的並且可以是任何東西,所以我不知道返回什么。
當我將一個空列表傳遞給我的尾巴函數時,返回Nil效果很好。
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
object List {
def sum(ints: List[Int]): Int = ints match {
case Nil => 0
case Cons(x,xs) => x + sum(xs)
}
def tail[A](xs: List[A]): List[A] = {
xs match {
case Cons(_, ys) => ys
case Nil => Nil
}
}
def head[A](as: List[A]): A = {
as match {
case Cons(b, _) => b
case Nil => Nil
}
}
}
object e31 {
def main(args: Array[String]): Unit = {
val ex3: List[Int] = Cons(1, Cons(2, Nil))
val ex2: List[Int] = Nil;
println(List.sum(ex3)) //3
println(List.tail(ex2)) //Nil
println(List.tail(ex3)) //cons(2, Nil)
//println(List.head(ex3)) //doesn't work
}
}
非常感謝您對理解問題的任何幫助。
def head[A](as: List[A]): Option[A] = as match {
case Cons(b, _) => Some(b)
case Nil => None
}
使head
返回Option
。 使用Option
可以傳達有時答案不可用或無效的答案。 例如:在這種情況下,當列表為空時, head
操作沒有任何意義。 因此,在這種情況下,我們返回None
值。 否則,當list為非空時,我們將返回Some
有效結果。
為了傳達結果並非總是可用,我們使用Option
作為返回類型
下面的代碼會導致編譯錯誤,因為您的返回類型為A
但實際上返回的是Nil
,其類型為List[A]
def head[A](as: List[A]): A = as match {
case Cons(b, _) => b
case Nil => Nil // expected A found: List[A]
}
請注意,此函數(返回選項(聲明以上)的頭)在std lib中稱為
headOption
有一種叫做Nothing
奇怪類型。 Nothing
是一切的子類型。 特別是, Nothing
是A
子類型(無論A
是什么)。 您不能產生Nothing
類型的任何值(此類型是unhabited )。 但是throw
關鍵字的行為就像它將“返回” Nothing
。 如果該操作是荒謬的,則可以執行帶有描述性錯誤消息的異常處理:
case Cons(h, _) => h
case Nil => throw new NoSuchElementException("`head` called on `Nil`")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.