Clojure – counting with recur

Counting the number of times something is seen is trivial in a mutable language such as python/perl/ruby. In immutable languages such as scala/clojure things are slightly different. To achieve something like this in clojure use the recur function rather than an all too tempting ref (my first solution, now lost).

(def some-data [1 2 2 3 3 3 4 4 4 4 5 5 5 5 5])

(defn counter [coll]
  (loop [ elt coll m {} ]
    (if (empty? elt) m
      (let [e (first elt) ] 
        ; the (+ (m e) 1) is better written as (inc (m e)) - according to a podcast I am listening to.
        (if (m e) (recur (rest elt) (assoc m e (+ (m e) 1) )) ( recur (rest elt) (assoc m e 1)))))))

(println (counter some-data))

The output of this code should be something like this:

biomunky@joshua:src$ clj fill-map-with-recur.clj 
{5 5, 4 4, 3 3, 2 2, 1 1}

I did something similar with scala here

There is probably a far better function in the contrib library, I simply haven’t looked…


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s