Skip to content

Instantly share code, notes, and snippets.

@kevinadi
Created May 10, 2016 07:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinadi/ec49b9c736dfe1ee33056194f652fcf7 to your computer and use it in GitHub Desktop.
Save kevinadi/ec49b9c736dfe1ee33056194f652fcf7 to your computer and use it in GitHub Desktop.
unfoldr in Scala
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