Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use reduce-kv over reduce in Clojure?

Tags:

clojure

What is the difference between reduce and reduce-kv?

When to use reduce-kv over reduce or vice versa?

like image 430
Ertuğrul Çetin Avatar asked Feb 11 '18 14:02

Ertuğrul Çetin


1 Answers

Whenever you're reducing associative collections, you should see a performance improvement when using reduce-kv due to it not allocating vectors/tuples for the key/value pairs. reduce will work on collections (and maps treated as collections of key/value tuples), but reduce-kv will only work on associative structures like maps and vectors.

From the IKVReduce protocol docstring:

"Protocol for concrete associative types that can reduce themselves via a function of key and val faster than first/next recursion over map entries. Called by clojure.core/reduce-kv, and has same semantics (just different arg order)."

The difference in using them is that you don't need to destructure the key/value in your reducing function:

(reduce (fn [m [k v]]
          (assoc m k (str v)))
        {}
        {:foo 1})

(reduce-kv (fn [m k v]
             (assoc m k (str v)))
           {}
           {:foo 1})
like image 91
Taylor Wood Avatar answered Nov 16 '22 02:11

Taylor Wood