Scala:Return 列表头但空列表不能 return Nil

Scala: Return head of list but empty list can't return Nil

我刚开始学习 Scala,我在使用 head 函数时遇到了一些麻烦。我想 return A 元素列表中的第一个元素。但是在 Nil 的情况下,我不知道 return。该函数需要 A,但由于 A 是抽象的并且可以是任何东西,所以我不知道 return 是什么。

当我将一个空列表传递给我的 tails 函数时 returning 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
}

制作headreturnOption。使用 Option 您可以传达有时答案不可用或无效的信息。例如:在这种情况下,当列表为空时,head 操作没有任何意义。所以,我们在这种情况下 return None 值。否则,当列表非空时,我们 return Some 有效结果。

为了表明结果并不总是可用,我们使用 Option 作为 return 类型

编译错误

下面的代码会导致编译错误,因为你的 return 类型是 A 但你实际上 return NilList[A][=24= 类型]

def head[A](as: List[A]): A = as match {
 case Cons(b, _) => b
 case Nil         => Nil // expected A found: List[A]
}

Note that this function (head which returns option (above declared)) is called headOption in std lib

有一种奇怪的类型叫做NothingNothing 是一切的子类型。特别是,NothingA 的子类型(无论 A 是什么)。您不能生成任何 Nothing 类型的值(此类型为 uninhabited)。但是 throw 关键字的行为 就好像它 "return" Nothing 一样。如果这个操作是无意义的,那么你可以做的就是抛出一个带有描述性错误信息的异常:

case Cons(h, _) => h
case Nil => throw new NoSuchElementException("`head` called on `Nil`")