Created
October 10, 2012 21:00
-
-
Save wspringer/3868378 to your computer and use it in GitHub Desktop.
Need something that wraps a traversable collection of tuples. Does this approach make sense at all?
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
/** | |
* A Traversable-alike abstraction of a traversable collection of tuples, without actually creating the tuples. | |
* I'd hope this would prevent me from polluting the heap with actual Tuple2 instances I never actually need. | |
*/ | |
trait Tuple2Traversable[+A, +B] { | |
def foreach[T](fn: (A, B) => T) | |
def map[T](fn: (A, B) => T): Traversable[T] = new Traversable[T] { | |
def foreach[U](f: (T) => U) { | |
def composed(a: A, b: B) = f(fn(a, b)) | |
Tuple2Traversable.this.foreach(composed) | |
} | |
} | |
def flatMap[T](fn: (A, B) => Traversable[T]): Traversable[T] = new Traversable[T] { | |
def foreach[U](f: (T) => U) { | |
def composed(a: A, b: B) = fn(a, b).foreach(f) | |
Tuple2Traversable.this.foreach(composed) | |
} | |
} | |
def filter(included: (A, B) => Boolean): Tuple2Traversable[A, B] = new Tuple2Traversable[A, B] { | |
def foreach[T](fn: (A, B) => T) { | |
def composed(a: A, b: B) = if (included(a, b)) fn(a, b) | |
Tuple2Traversable.this.foreach(composed) | |
} | |
} | |
def foldLeft[T](z: T)(fn: (T, A, B) => T): T = { | |
var current = z | |
def op(a: A, b: B) { | |
current = fn(current, a, b) | |
} | |
foreach(op) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added foldLeft alike operation.