Skip to content

Instantly share code, notes, and snippets.

@sledorze
Created February 3, 2012 10:16
Show Gist options
  • Save sledorze/1729506 to your computer and use it in GitHub Desktop.
Save sledorze/1729506 to your computer and use it in GitHub Desktop.
unfold in Scala
final class Unfoldable[A](a : A){
def unfold[B, This, That](f: A => Option[(B, A)])(implicit cb: CanBuildFrom[This, B, That]): That = {
val builder = cb()
@tailrec def unfolding(a: A) : That = {
f(a) match {
case Some((e, next)) =>
builder += e
unfolding(next)
case None =>
builder.result()
}
}
unfolding(a)
}
}
implicit def toUnfoldable[A](a: A) = new Unfoldable (a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment