Created
May 11, 2011 21:14
-
-
Save kputnam/967371 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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