Skip to content

Instantly share code, notes, and snippets.

@kputnam
Created May 11, 2011 21:14
Show Gist options
  • Save kputnam/967371 to your computer and use it in GitHub Desktop.
Save kputnam/967371 to your computer and use it in GitHub Desktop.
object Unfold {
/**
* Builds a list by recursively applying `f`, until `f` returns None
*
* @param seed the initial value passed to `f`
* @param f returns Some(Pair(element, nextSeed)) where `element` is added
* to the list and `nextSeed` is passed to `f` on the next invocation.
*/
def buildList[T, R](seed: T)(f: T => Option[Pair[R, T]]): List[R] =
f(seed) match {
case None => List.empty
case Some(Pair(e, succ)) => e :: buildList(succ)(f)
}
/**
* Builds a stream by recursively applying `f`, until `f` returns None
*
* @param seed the initial value passed to `f`
* @param f returns Some(Pair(element, nextSeed)) where `element` is added
* to the stream and `nextSeed` is passed to `f` on the next invocation.
*/
def buildStream[T, R](seed: T)(f: T => Option[Pair[R, T]]): Stream[R] =
f(seed) match {
case None => Stream.empty
case Some(Pair(e, succ)) => Stream.cons(e, buildStream(succ)(f))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment