Created
June 18, 2013 19:23
-
-
Save aamedina/5808416 to your computer and use it in GitHub Desktop.
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
defn pmap | |
"Like map, except f is applied in parallel. Semi-lazy in that the | |
parallel computation stays ahead of the consumption, but doesn't | |
realize the entire result unless required. Only useful for | |
computationally intensive functions where the time of f dominates | |
the coordination overhead." | |
{:added "1.0" | |
:static true} | |
([f coll] | |
(let [n (+ 2 (.. Runtime getRuntime availableProcessors)) | |
rets (map #(future (f %)) coll) | |
step (fn step [[x & xs :as vs] fs] | |
(lazy-seq | |
(if-let [s (seq fs)] | |
(cons (deref x) (step xs (rest s))) | |
(map deref vs))))] | |
(step rets (drop n rets)))) | |
([f coll & colls] | |
(let [step (fn step [cs] | |
(lazy-seq | |
(let [ss (map seq cs)] | |
(when (every? identity ss) | |
(cons (map first ss) (step (map rest ss)))))))] | |
(pmap #(apply f %) (step (cons coll colls)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment