Created
March 15, 2009 15:06
-
-
Save DRMacIver/79443 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| object builders { | |
| trait Builder[From, To, Elem1] { | |
| def += (elem: Elem1) | |
| def result: To | |
| } | |
| implicit def listBuilder[A, B] = new Builder[List[A], List[B], B] { | |
| private val buf = new scala.collection.mutable.ListBuffer[B] | |
| def += (elem: B) { buf += elem } | |
| def result: List[B] = buf.toList | |
| } | |
| implicit def arrayBuilder[A, B] = new Builder[Array[A], Array[B], B] { | |
| private val buf = new scala.collection.mutable.ListBuffer[B] | |
| def += (elem: B) { buf += elem } | |
| def result: Array[B] = buf.toArray | |
| } | |
| class Iter[A, C](elems: List[A]) { | |
| def ++ [B >: A, D](xs: Iterable[B])(implicit b: Builder[C, D, B]): D = { | |
| for (x <- elems) b += x | |
| for (x <- xs) b += x | |
| b.result | |
| } | |
| def map[B, D](f: A => B)(implicit b: Builder[C, D, B]): D = { | |
| for (x <- elems) b += f(x) | |
| b.result | |
| } | |
| } | |
| def main(args : Array[String]) : Unit = { | |
| val x = new Iter[Int, List[Int]](List(1, 2, 3)) | |
| val y: List[Int] = x.map (_ + 1) | |
| println(y) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment