I have am trying something in scala worksheet in eclipse. This is not showing any output , and doesn't show any error or warning either.
object stream {
println("Welcome to the Scala worksheet")
def cons[T](hd: T, t1: => Stream[T]): Stream[T] = new Stream[T] {
def head = hd
private var t1Opt: Option[Stream[T]] = None
def tail: Stream[T] = t1Opt match {
case Some(x) => x
case None => t1Opt = Some(t1); tail
}
}
def streamIncrementedby2(x: Int): Stream[Int] = x #:: streamIncrementedby2(x + 2)
val x = this.cons(-1, this.streamIncrementedby2(5))
println(x.head)
}
I am trying out the example in the courera odersky course: scala functional design week3 video. Interestingly in the above example, if I remove everything below the first println statement, I see an evaluated output.
******* Update ******** To help other readers , I am posting corrected version of the above program , inspired by the answer.
def cons[T](hd: T, t1: => Stream[T]) = new Stream[T] {
override def head = hd
override def isEmpty = false
private[ this ] var t1Opt: Option[Stream[T]] = None
def tailDefined: Boolean = true
override def tail: Stream[T] = t1Opt match {
case Some(x) => x
case None => {t1Opt = Some(t1); tail}
}
}