Created
March 22, 2014 15:07
-
-
Save orionll/9708659 to your computer and use it in GitHub Desktop.
Effective fold() implementation for IndexedSeq
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
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