Scala工作表抛出错误
在IntelliJ(使用Scala 2.11.8)上运行Scala代码时出错: 我的Scala工作表有:Scala工作表抛出错误,scala,intellij-idea,Scala,Intellij Idea,在IntelliJ(使用Scala 2.11.8)上运行Scala代码时出错: 我的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 Con
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)未找到:类型Cons
lazy val l1=新Cons(1,新Cons(2,新Cons(2,新Nil)))
^
错误:(6,16)值-不是类型参数T的成员
第n(n-1,左尾)
^您的
n
通过T
参数化。在它内部,您使用n(n-1,…)
递归调用它
n-1
的类型是什么n
的类型为T
,1
的类型为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)
}
编辑
将我的代码版本放在一个类中,该类扩展了应用程序。我已经放弃使用工作表了。太不可靠或隐藏的秘密太多
第二辑
右键单击工作表,按下Recompile.sc
和Run
.sc`,它就工作了。。。哦,工作表
即使将
T
更改为Int
,也会有一个红色的-
符号。。这应该是另一个问题,你是对的。需要显式参数化:)您必须首先编译week4包,然后尝试运行工作表。至少它对我来说没有任何代码变化
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)
}