在 SCALA 中查找常规类型的第 N 个元素会抛出 NoSuchElementException



在下面的代码中:

object example {
trait List[T] {
def isEmpty: Boolean
def head: T
def tail: List[T]
}
class Cons[T](val head: T, val tail: List[T]) extends List[T] {
def isEmpty: Boolean = false
}
class Nil[T] extends List[T] {
def isEmpty: Boolean = true
val head: Nothing = throw new NoSuchElementException("Nil.head")
val tail: Nothing = throw new NoSuchElementException("Nil.tail")
}

def nth[T](n: Int, xs: List[T]): T =
if (xs.isEmpty) throw new IndexOutOfBoundsException("Out of Bound")
else if (n == 0) xs.head
else nth(n - 1, xs.tail)
val list = new Cons(1, new Cons(2, new Cons(3, new Nil)))
nth(2,list) //should return 3
}

我试图定义一个一般特征List[T]所以以后我可以给它任何类型。我可以从中实现我的类,然后我定义了一个函数,它接受一个整数和一个列表,并返回位于第 n 个给定索引处的元素。val list = new Cons(1, new Cons(2, new Cons(3, new Nil)))抛出NoSuchElementException.我认为我的代码有一个基本问题,我可以弄清楚。 顺便说一下,我正在运行它的 REPL。谢谢。

请更正以下行

val head: Nothing = throw new NoSuchElementException("Nil.head")
val tail: Nothing = throw new NoSuchElementException("Nil.tail")

def head: Nothing = throw new NoSuchElementException("Nil.head")
def tail: Nothing = throw new NoSuchElementException("Nil.tail")

Nil中,你定义headtailval,所以这些语句在你实例化Nil时执行,导致错误。

将它们更改为def head: Nothing = ...def tail: Nothing = ...

最新更新