简体   繁体   English

为什么Nil无法创建?

[英]Why Object Nil can't create?

Having the error: 出现错误:

Object creation impossible, since member node: Option[(A, MyModule.List[A])] in MyModule.List is not defined 无法创建对象,因为未定义成员节点: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: _*)) 
In this case, how to implement? 在这种情况下,如何实施? I wonder what functions should be put in trait and what functions should be put in Company Object. 我想知道应将哪些功能放入特征中,应将哪些功能放入公司对象中。

Here is correct implementation: 这是正确的实现:

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: _*))
  }
}

I see few problems here: 我在这里看到一些问题:

1) You have two implementation of cons you can implement cons method simpler: 1)您有两个cons实现,可以更简单地实现cons方法:

  def cons[A](head: A, tail: List[A]) = Cons(head, tail)

2) Same with empty 2)与empty相同

  def empty[A] = Nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM