Created
February 3, 2012 10:16
-
-
Save sledorze/1729506 to your computer and use it in GitHub Desktop.
unfold 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
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