Created
June 24, 2010 04:26
-
-
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}
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
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