为什么Nil无法创建?

时间:2018-11-15 03:28:02

标签: scala

出现错误:

由于成员节点: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: _*))
在这种情况下,如何实施? 我想知道应将哪些功能放入特征中,应将哪些功能放入公司对象中。

1 个答案:

答案 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
相关问题