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 –