answerkey/laziness/16.answer.md
/*
The function can't be implemented using `unfold`, since `unfold` generates elements of the `LazyList` from left to right. It can be implemented using `foldRight` though.
The implementation is just a `foldRight` that keeps the accumulated value and the lazy list of intermediate results, which we `cons` onto during each iteration. When writing folds, it's common to have more state in the fold than is needed to compute the result. Here, we simply extract the accumulated list once finished.
*/
def scanRight[B](init: B)(f: (A, => B) => B): LazyList[B] =
foldRight(init -> LazyList(init)): (a, b0) =>
// b0 is passed by-name and used in by-name args in f and cons. So use lazy val to ensure only one evaluation...
lazy val b1 = b0
val b2 = f(a, b1(0))
(b2, cons(b2, b1(1)))
._2