Clojure symbol counting

One of the little things I found enjoyable while trying out Clojure was discovering the merge-with command. After counting the each of the subbranch and collecting the results in dictionaries, the dictionaries were merged together.

clojure.core/merge-with
([f & maps])
  Returns a map that consists of the rest of the maps conj-ed onto
  the first.  If a key occurs in more than one map, the mapping(s)
  from the latter (left-to-right) will be combined with the mapping in
  the result by calling (f val-in-result val-in-latter).

Using merge-with yields a rather terse code, comprising a tree-walker and a final tally.


(defn count-syms
  "count number time of a symbol occurs in the first place of a sequence"
  [obj]
  (if (not (seq? obj))
      {} ; only count sequences
      (do
        (reduce #(merge-with + %1 %2)
          (conj
            (map
                count-syms
                (filter seq? (rest obj)))
            (inc-dict dict (first obj)))))))

You should follow me on twitter here

Leave a Reply