Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeremy.Stone authored and Jeremy.Stone committed Nov 5, 2014
1 parent ecda0f8 commit 650cfc3
Show file tree
Hide file tree
Showing 5 changed files with 19 additions and 18 deletions.
14 changes: 12 additions & 2 deletions answerkey/laziness/16.answer.scala
@@ -1,2 +1,12 @@
def hasSubsequence[A](s: Stream[A]): Boolean =
tails exists (_ startsWith s)
/*
The function can't be implemented using `unfold`, since `unfold` generates elements of the `Stream` from left to right. It can be implemented using `foldRight` though.
The implementation is just a `foldRight` that keeps the accumulated value and the stream 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](z: B)(f: (A, => B) => B): Stream[B] =
foldRight((z, Stream(z)))((a, p0) => {
// p0 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 p1 = p0
val b2 = f(a, p1._1)
(b2, cons(b2, p1._2))
})._2
2 changes: 1 addition & 1 deletion answerkey/laziness/16.hint.txt
@@ -1 +1 @@
-
The function can't be implemented using `unfold`, since `unfold` generates elements of the `Stream` from left to right. It can be implemented using `foldRight` though.
10 changes: 0 additions & 10 deletions answerkey/laziness/17.answer.scala

This file was deleted.

1 change: 0 additions & 1 deletion answerkey/laziness/17.hint.txt

This file was deleted.

10 changes: 6 additions & 4 deletions answers/src/main/scala/fpinscala/laziness/Stream.scala
Expand Up @@ -182,10 +182,12 @@ trait Stream[+A] {
The implementation is just a `foldRight` that keeps the accumulated value and the stream 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](z: B)(f: (A,=>B) => B): Stream[B] =
foldRight((z, Stream(z)))((a,p) => {
val b2 = f(a,p._1)
(b2, cons(b2,p._2))
def scanRight[B](z: B)(f: (A, => B) => B): Stream[B] =
foldRight((z, Stream(z)))((a, p0) => {
// p0 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 p1 = p0
val b2 = f(a, p1._1)
(b2, cons(b2, p1._2))
})._2

@annotation.tailrec
Expand Down

0 comments on commit 650cfc3

Please sign in to comment.