Skip to content

Instantly share code, notes, and snippets.

@anrizal06
Created September 5, 2011 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anrizal06/1195982 to your computer and use it in GitHub Desktop.
Save anrizal06/1195982 to your computer and use it in GitHub Desktop.
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