出现错误:
由于成员节点:MyModule.List中的Option [(A,MyModule.List [A])]未定义,因此无法创建对象
sealed trait List[+A] {
def node: Option[(A, List[A])]
def isEmpty = node.isEmpty
}
abstract class Cons[+A](head: A, tail: List[A]) extends List[A]
object Nil extends List[Nothing]
object List {
def empty[A] = new List[A] { def node = None }
def cons[A](head: A, tail: List[A]) = new List[A] { def node = Some((head, tail)) }
def apply[A](as: A*):List[A] = {
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
答案 0 :(得分:0)
这是正确的实现:
sealed trait List[+A] {
def node: Option[(A, List[A])]
def isEmpty = node.isEmpty
}
case class Cons[+A](head: A, tail: List[A]) extends List[A] {
override def node: Option[(A, List[A])] = Some((head, tail))
}
object Nil extends List[Nothing] {
override def node: Option[(Nothing, List[Nothing])] = None
}
object List {
def empty[A] = new List[A] {
def node = None
}
def cons[A](head: A, tail: List[A]) = new List[A] {
def node = Some((head, tail))
}
def apply[A](as: A*): List[A] = {
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
}
}
我在这里看到了几个问题:
1)您有两种实施缺点
您可以更简单地实现cons
方法:
def cons[A](head: A, tail: List[A]) = Cons(head, tail)
2)与empty
def empty[A] = Nil