Skip to content

Commit

Permalink
Merge pull request #335 from jeremystone/master
Browse files Browse the repository at this point in the history
Issue #334
  • Loading branch information
pchiusano committed Dec 15, 2014
2 parents 3cfc654 + 650cfc3 commit 1f6b487
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 @@ -177,10 +177,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 1f6b487

Please sign in to comment.