Is there a benefit to build a Stream in a tail-recursive way with an accumulator? The @tailrec annotation will turn a recursion into a loop, but the loop would be evaluated strictly.
I can figure out a simple way to add at the head of the stream in a tail-recursive way
@tailrec
def toStream(current:A, f: A => B, next: A => A, previous:Stream[B]):Stream[B]] = {
if(exitCondition(a))
previous
else{
val newItem = f(current)
val newCurrent = next(a)
toStream(nextCurrent,f,next,Stream cons (newItem, previous) )
}
}
And how to add at the end (building a real lazy stream) without tail-recursion
def toStream(current:A, f: A => B, next: A => A):Stream[B] = {
if(exitCondition(a))
Stream.empty[B]
else{
val newItem = f(current)
val newCurrent = next(a)
Stream.cons (newItem, toStream(newCurrent))
}
}
How would you code the dual of this function:
- Add at the head in non tail-recursive?
- Add the end tail-recursive