Last active
August 29, 2015 14:16
-
-
Save jgrimes/c0e048c8a0b8bc9efd7b to your computer and use it in GitHub Desktop.
reducing multiple functions
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
lambda.match> (time (sidelong-count-and-sum (range 100000000))) | |
"Elapsed time: 89361.517429 msecs" | |
[100000000 4999999950000000] | |
lambda.match> (time (reduce #((juxt | |
(partial (fn [x y] (+ x 1)) (first %)) ; count | |
(partial + (second %))) ; sum | |
%2) | |
[1 0] | |
(range 1 100000000))) | |
"Elapsed time: 51670.058838 msecs" | |
[100000000 4999999950000000] | |
; the macro is faster than the function below since it | |
; creates the juxted function statically | |
(defmacro reduce-multi [fns init args] | |
(let [acc (gensym) | |
n (gensym)] | |
`(reduce (fn [~acc ~n] | |
[~@(map-indexed (fn [arg# f#] `(~f# (nth ~acc ~arg#) ~n)) fns)]) | |
~init | |
~args))) | |
(defn reduce-multi [fns init args] | |
(reduce (fn [acc n] | |
((apply juxt | |
(map-indexed #(partial %2 (nth acc %)) fns)) | |
n)) | |
init | |
args)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reducer version, theoretically data-parallel via fork/join. Uses a map instead of tuple to simplify merging and avoid accidental
seq
. A vector would work too, it's more a matter of taste considering both types can be reducer'd.