Scala工作表抛出错误

时间:2017-08-15 14:18:31

标签: scala intellij-idea

我在IntelliJ上运行我的Scala代码时遇到错误(使用Scala 2.11.8):

package week4

/**
  * Created by BigB on 15/08/17.
  */
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] {
  override def isEmpty: Boolean = false
}

class Nil[T] extends List[T] {
  override def isEmpty: Boolean = true

  override def head: T = throw new NoSuchElementException("Nil.head")

  override def tail: List[T] =throw new NoSuchElementException("Nil.tail")
}

我的Scala工作表有:

import week4._

object nth {
  def nth[T](n: T, l: List[T]): T = {
    if (l.isEmpty) throw new IndexOutOfBoundsException
    else if (n==0) l.head
    else nth(n-1, l.tail)
  }

  val l1 = new Cons(1, new Cons(2, new Cons(2, new Nil)))

  nth(2, l1)
}

错误:

错误:(9,20)未找到:输入缺点 lazy val l1 = new Cons(1,new Cons(2,new Cons(2,new Nil)))                   ^

错误:(6,16)value - 不是类型参数T的成员     否则nth(n-1,l.tail)               ^

1 个答案:

答案 0 :(得分:1)

您的nth参数化为T。在其中,您可以使用nth(n-1, ...)递归调用它。

n-1的类型是什么? n类型为T1类型为Int,结果类型无法推断为T类型,因此无效。

我建议传递一个额外的参数,或许:

object nth {
  def nth[T](n: T, l: List[T], dec: T => T): T = {
    if (l.isEmpty) throw new IndexOutOfBoundsException
    else if (n==0) l.head
    else nth[T](dec(n), l.tail, dec)
  }

  val l1 = new Cons(1, new Cons(2, new Cons(2, new Nil)))

  nth[Int](2, l1, _ - 1)
}

修改

将我的代码版本放在extends App按预期工作的类中。我放弃了使用工作表。太不可靠或太多隐藏的秘密。

编辑2号

右键单击按下Recompile <ws>.scRun。sc`的工作表,它工作正常......哦工作表好!

enter image description here

相关问题