Back to Fpinscala

14.Answer

answerkey/laziness/14.answer.md

latest580 B
Original Source
scala
/*
`s.startsWith(s2)` when corresponding elements of `s` and `s2` are all equal, until the point that `s2` is exhausted. If `s` is exhausted first, or we find an element that doesn't match, we terminate early. Using non-strictness, we can compose these three separate logical steps--the zipping, the termination when the second lazy list is exhausted, and the termination if a nonmatching element is found or the first lazy list is exhausted.
*/
def startsWith[A](prefix: LazyList[A]): Boolean =
  zipAll(prefix).takeWhile(_(1).isDefined).forAll((a1, a2) => a1 == a2)