I am looking at exercise 5.8 in book "FP in Scala" and the question is:
"Generalize ones slightly to the function constant, which returns an infinite Stream of a given value."
def constant[A](a: A): Stream[A]
My solution is:
def constant[A](a: A): Stream[A] =
Stream.cons(a, constant(a))
while I refer to the standard solution, it was:
// This is more efficient than `cons(a, constant(a))` since it's just
// one object referencing itself.
def constant[A](a: A): Stream[A] = {
lazy val tail: Stream[A] = Cons(() => a, () => tail)
tail
}
which says "more efficient", see here.
Can I know why is it more efficient? AFAIK, the cons constructor in Streams already marks the head and tail as lazy:
def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = {
lazy val head = hd
lazy val tail = tl
Cons(() => head, () => tail)
}
Why do we still need to mark the tail as lazy again? I am not quite understand the point here.