我試圖從Functional Programming in Scala解決練習2。問題如下:執行流的錯誤
練習2:編寫一個函數,用於返回流的前n個元素 。 def採取(N:智力):流[A]
我的解決方案如下:
import Stream._
trait Stream[+A]{
def uncons:Option[(A,Stream[A])]
def isEmpty:Boolean = uncons.isEmpty
def toList:List[A] = {
val listBuffer = new collection.mutable.ListBuffer[A]
@annotation.tailrec
def go(str:Stream[A]):List[A] = str uncons match {
case Some((a,tail)) => listBuffer += a;go(tail)
case _ => listBuffer.toList
}
go(this)
}
def take(n:Int):Stream[A] = uncons match {
case Some((hd,tl)) if (n > 0) => cons(hd,tl.take(n-1))
case _ => Stream()
}
}
object Stream{
def empty[A]:Stream[A] = new Stream[A]{def uncons = None}
def cons[A](hd: => A,tl: => Stream[A]):Stream[A] = new Stream[A]{
lazy val uncons = Some((hd,tl))
}
def apply[A](as: A*):Stream[A] = {
if(as.isEmpty) empty else
cons(as.head,apply(as.tail: _ *))
}
}
我存儲此作爲Stream2.scala然後從我執行以下的REPL:
:load Stream2.scala
當REPL嘗試加載我的腳本,它與barfs以下錯誤:
斯卡拉>:負載STREA m2.scala
Loading Stream2.scala...
import Stream._
<console>:24: error: type mismatch;
found : Stream[A]
required: scala.collection.immutable.Stream[?]
case Some((hd,tl)) if (n > 0) => cons(hd,tl.take(n-1))
^
<console>:25: error: type mismatch;
found : scala.collection.immutable.Stream[Nothing]
required: Stream[A]
case _ => Stream()
^
<console>:11: error: object creation impossible, since method tailDefined in class Stream of type => Boolean is not defined
def empty[A]:Stream[A] = new Stream[A]{def uncons = None}
^
<console>:12: error: object creation impossible, since method tailDefined in class Stream of type => Boolean is not defined
def cons[A](hd: => A,tl: => Stream[A]):Stream[A] = new Stream[A]{
有人能指出什麼可能是錯誤怎麼回事?
嘗試在REPL之外執行此操作 - 使用' scalac Stream2.scala'。這可能是因爲REPL沒有將伴侶對象連接到「Stream」特性。此外似乎還有一些來自標準庫Stream的干擾(與Stream的共享名稱相同)。在REPL外編譯可能會提供更長的錯誤消息。 – huynhjl
或使用':paste'。 –
或者來到你附近的repl,也許,粘貼文件,https://issues.scala-lang.org/browse/SI-4684 –