Back to Fpinscala

12.Answer

answerkey/laziness/12.answer.md

latest717 B
Original Source
scala
/*
Scala provides shorter syntax when the first action of a function literal is to match on an expression.  The function passed to `unfold` in `fibsViaUnfold` is equivalent to `p => p match { case (f0,f1) => ... }`, but we avoid having to choose a name for `p`, only to pattern match on it.
*/
val fibsViaUnfold: LazyList[Int] =
  unfold((0,1)):
    case (current, next) =>
      Some((current, (next, current + next)))

def fromViaUnfold(n: Int): LazyList[Int] =
  unfold(n)(n => Some((n, n + 1)))

def continuallyViaUnfold[A](a: A): LazyList[A] =
  unfold(())(_ => Some((a, ())))

// could also of course be implemented as constant(1)
val onesViaUnfold: LazyList[Int] =
  unfold(())(_ => Some((1, ())))