Skip to content

Instantly share code, notes, and snippets.

@retronym
Created June 24, 2010 04:26
Show Gist options
  • Save retronym/450979 to your computer and use it in GitHub Desktop.
Save retronym/450979 to your computer and use it in GitHub Desktop.
List.unfold(0){ a => if (a < 10) Some(a + 1, a.toString) else None}
import scala.collection.generic._
object RichTraversableCompanion {
implicit def pimp[CC[X] <: Traversable[X] with GenericTraversableTemplate[X, CC], T](comp: TraversableFactory[CC]) = new RichTraversableCompanion[CC](comp)
}
class RichTraversableCompanion[CC[X] <: Traversable[X] with GenericTraversableTemplate[X, CC]](comp: TraversableFactory[CC]) {
def unfold[A, B](seed: A)(f: A => Option[(A, B)]): CC[B] = {
val builder = comp.newBuilder[B]
@annotation.tailrec
def loop(a: A): Unit = f(a) match {
case Some((a, b)) => builder += b; loop(a)
case None =>
}
loop(seed)
builder.result
}
def iterateWhile[A](seed: A)(f: A => Option[A]): CC[A] = {
val builder = comp.newBuilder[A]
@annotation.tailrec
def loop(a: A): Unit = f(a) match {
case Some(a) => builder += a; loop(a)
case None =>
}
loop(seed)
builder.result
}
}
import RichTraversableCompanion._
List.unfold(0) {a => if (a < 10) Some(a + 1, a.toString) else None}
Stream.unfold(0) {a => if (a < 10) Some(a + 1, a.toString) else None}
Vector.unfold(0) {a => if (a < 10) Some(a + 1, a.toString) else None}
Vector.iterateWhile(0) {a => if (a < 10) Some(a + 1) else None}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment