1
我正在通过一些练习:斯卡拉函数式编程特别是问题5.2。问题是,我用答案关键字拼凑了以下代码。斯卡拉错误的前向参考
sealed trait Stream[+A]
{
def take(n: Int): Stream[A] = this match {
case Cons(hs, ts) if n > 1 => cons(h(), t().take(n - 1))
case Cons(hs, _) if n == 1 => cons(h(), empty)
case _ => empty
}
}
case object Empty extends Stream[Nothing]
case class Cons[+A](h:() => A, t:() => Stream[A]) extends Stream[A]
object Stream{
def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = {
lazy val head = hd
lazy val tail = tl
Cons(() => head ,() => tail)
}
def empty[A]: Stream[A] = Empty
def apply[A](as: A*): Stream[A] =
if (as.isEmpty) empty
else cons(as.head, apply(as.tail: _*))
}
我得到的REPL如下:
<console>:10: error: not found: type A
def take(n: Int): Stream[A] = this match {
^
<console>:11: error: not found: value Cons
case Cons(hs, ts) if n > 1 => cons(h(), t().take(n - 1))
^
<console>:11: error: not found: value cons
case Cons(hs, ts) if n > 1 => cons(h(), t().take(n - 1))
^
<console>:12: error: not found: value Cons
case Cons(hs, _) if n == 1 => cons(h(), empty)
^
<console>:12: error: not found: value cons
case Cons(hs, _) if n == 1 => cons(h(), empty)
^
<console>:13: error: not found: value empty
case _ => empty
^
谢谢!我正在使用intellij,并且导入效果很好,但显式指定对象时虽然两者都值得用REPL。我认为变量名称在我试图伸手去拿秸秆的时候就会出现一些错误......可以这么说。 –
嗯,这很奇怪,对象表示法不起作用。也许还有其他类干扰?也许你已经导入了'scala.collection.Stream'?如果我到这里并粘贴这段代码,那么它编译得很好:http://www.tutorialspoint.com/compile_scala_online.php –