case object Empty extends Stream[Nothing]
case class Cons[+A](h:() => A, t:() => Stream[A]) extends Stream[A]
sealed trait Stream[+A] {
def toList: List[A] = {
val buf = new collection.mutable.ListBuffer[A]
def go(s: Stream[A]): List[A] = s match {
case Cons(h, t) =>
buf += h()
go(t())
case _ => buf.toList
}
go(this)
}
def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = Stream.cons(hd, tl)
def empty = Stream.empty
def unfold[A, S](z: S)(f: S => Option[(A, S)]): Stream[A] = f(z) match {
case Some((h,t)) => cons(h, unfold(t)(f))
case None => empty
}
def take(n: Int): Stream[A] = unfold((this, n)) {
case (Cons(h, t), 1) => Some((h(), (empty, 0)))
case (Cons(h, t), n) if n > 1 => Some((h(), (t(), n-1)))
case (Empty, 0) => None
}
}
object Stream {
def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = Cons(() => hd,() => tl)
def empty[A]: Stream[A] = Empty
val ones: Stream[Int] = Stream.cons(1, ones)
}
object StreamTest {
def main(args: Array[String]) {
//why compile error: forward reference extends over definition of value ones
/*val ones: Stream[Int] = Stream.cons(1, ones)
println(ones.take(5).toList)*/
println(Stream.ones.take(5).toList)
}
}
क्यों संकलन त्रुटि परिभाषा पर फैली ?: आगे संदर्भ मूल्य वालेस्केला आगे संदर्भ
जोड़ी वस्तु 'स्ट्रीम' मेंकी परिभाषा पर फैली, वैल वाले: स्ट्रीम [इंट] = Stream.scons (1, वाले) ठीक है
लेकिन मुख्य विधि में, यह ठीक नहीं है (लेकिन ... एक ही सिंथेटिक!)
@mz कृपया मुख्य विधि में टिप्पणी चिह्न (/ * * /) हटाएं, '/ * वैल वाले: स्ट्रीम [Int] = Stream.cons (1, ones) println (ones.take (5) .toist) */' – Curycu