Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Implementation of solution 3 from (Pope, 2010 ?) in Scala
// 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