Created
September 5, 2011 21:38
-
-
Save anrizal06/1195982 to your computer and use it in GitHub Desktop.
Implementation of solution 3 from (Pope, 2010 ?) in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To simplify the implementation, foldr_ is introduced. It is the foldr function with a modification in | |
// combine parameter. Instead of (A, =>B) => B, combine has type (A, B, Stream[A])=>B. | |
// This makes combine has an easy access to the stream being processed. | |
// There might be another way to implement the solution, but this one is the one that comes into my head so far. | |
def foldr_[A, B]( combine: (A, =>B, Stream[A]) => B, base: B)( xs: Stream[A]): B = { | |
if (xs.isEmpty) | |
base | |
else | |
combine(xs.head, foldr_(combine, base)(xs.tail), xs) | |
} | |
// And here is the implementation of dropWhile | |
def dwTailFree[A](pred:A=>Boolean, xs:Stream[A]) = { | |
def combine(next:A, rec: =>Stream[A]=> Stream[A], s:Stream[A]) = { | |
if (pred(next)) (_:Stream[Int])=>rec(s.tail) | |
else (_:Stream[Int])=>s | |
} | |
val id =(s:Stream[Int])=>s | |
foldr_(combine,id)(xs) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment