Skip to content

Instantly share code, notes, and snippets.

@wspringer
Created October 10, 2012 21:00
Show Gist options
  • Save wspringer/3868378 to your computer and use it in GitHub Desktop.
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?
/**
* 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)
}
}
@wspringer
Copy link
Author

In any case, you don't have the benefit of having the ability to use for comprehensions.

@wspringer
Copy link
Author

Added foldLeft alike operation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment