r/mit6824clojure • u/TheLastSock • Jun 28 '20
None distributed but multithread map reduce in clojure
Most clojure devs are familiar with map and reduce which are in clojure core
(->> [1 2 3]
(map inc)
(reduce +))
=> 9But there is another library in clojure that provides parallelism, its part of reducers:
(require '[clojure.core.reducers :as r])example pulled right from clojure docs
(defn count-occurrences [coll]
(r/fold
(r/monoid #(merge-with + %1 %2) (constantly {})) ;
(fn [m [k cnt]] (assoc m k (+ cnt (get m k 0)))) ;
(r/map #(vector % 1) (into [] coll)))) ;
(defn word-count [s]
(count-occurrences (.split #"\s+" s)))
(def war-and-peace "http://www.gutenberg.org/files/2600/2600-0.txt")
(def book (slurp war-and-peace))
(def freqs (word-count book))
(freqs "Andrew")
;
breaking this down
folds signature looks like this:
([reducef coll])
([combinef reducef coll] )
([n combinef reducef coll]))so this example here we can label the inputs so we can visualize better whats going on...
(defn count-occurrences [coll]
(r/fold
(r/monoid #(merge-with + %1 %2) (constantly {})) combinef
(fn [m [k cnt]] (assoc m k (+ cnt (get m k 0)))) reducef
(r/map #(vector % 1) (into [] coll)))) collthis operates over a multi threaded fork and join model to do map reduce in parallel. we should the arguments to fold from bottom to top follows the way things are processed
coll : the initial collection is split into chunks. e.g [hello 1] [hello 1] ...
reducef : this is where i believe individual jobs (thread, etc..) reduce the work there given so on a thread. you would see [hello 1] [hello 1] -> {:hello 2} as we add our words together
combinef** : this is where i believe the final "combining" effort is done across our works. Note, it's possible this logic is a duplicate of what reducef is going (hense the function arity with only 2 arguments). but in our case work on the prev thread {:hello 2} might be combined with another to yield {:hello 5}.
Note this isn't distributed in the sense that it runs across multiple computers, but some of the principles are the same. I was skimming over clojure core and hit this topic (again) and thought it would be interesting to share given the lecture topic this week (map reduce).
** i have no idea what -r/monoid is doing.
* title should read non-distributed
1
u/ErnestoGarciaGarcia Jul 27 '20
Thanks for sharing, I didn't know this existed in the Clojure std lib. r/monoid is defining the combinef function, which should be a monoid (a set with a closed associative operation with an identity zero element).