Skip to content

Instantly share code, notes, and snippets.

@orionll
Created March 22, 2014 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orionll/9708659 to your computer and use it in GitHub Desktop.
Save orionll/9708659 to your computer and use it in GitHub Desktop.
Effective fold() implementation for IndexedSeq
def myFold[A](seq: IndexedSeq[A])(z: A)(f: (A, A) => A): A = {
// Divide the sequence into to halfes and then combine the results
def recur(from: Int, to: Int): A = {
if (from > to) {
z
} else if (from == to) {
seq(from)
} else {
f(recur(from, from + (to - from) / 2), recur(from + (to - from) / 2 + 1, to))
}
}
recur(0, seq.length - 1)
}
// Performance tests:
val vec = Vector.fill(1000000)("a")
val result = myFold(vec)("")((x, y) => x + y) // Takes 182,0 ms on my machine
val result2 = vec.fold("")((x, y) => x + y) // Doesn't finish in reasonable amount of time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment