Created
May 10, 2016 07:09
-
-
Save kevinadi/ec49b9c736dfe1ee33056194f652fcf7 to your computer and use it in GitHub Desktop.
unfoldr 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
def unfoldr[A, B](seed: B)(func: B => Option[(A, B)]): Stream[A] = | |
func(seed) match { | |
case Some((a, b)) => a #:: unfoldr(b)(func) | |
case None => Stream.empty | |
} | |
/* | |
* Infinite sequence: | |
* val s = unfoldr (0) (b => Some(b,b+1)) | |
* Fibonacci sequence: | |
* val fibs = unfoldr ((BigInt(1),BigInt(1))) {b => Some(b._1, (b._2, b._1 + b._2))} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment