Scala:返回列表头但空列表不能返回Nil

问题描述 投票:0回答:2

我刚刚开始学习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

    }
}

非常感谢任何帮助理解这个问题。

scala list functional-programming traits
2个回答
2
投票

Option to the rescue

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作为返回类型

Compilation error

下面的代码导致编译错误,因为你的返回类型是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


2
投票

这种奇怪的类型叫做NothingNothing是一切的子类型。特别是,NothingA的子类型(无论A是什么)。您不能生成Nothing类型的任何值(此类型无人居住)。但throw关键字的行为就好像它会“返回”Nothing。如果操作是无意义的,那么您可以执行以下操作:抛出带有描述性错误消息的异常:

case Cons(h, _) => h
case Nil => throw new NoSuchElementException("`head` called on `Nil`")
© www.soinside.com 2019 - 2024. All rights reserved.