Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure reduce function

Tags:

clojure

I am trying to understand this function from clojuredocs.org:

;; Create a word frequency map out of a large string s.

;; `s` is a long string containing a lot of words :)
(reduce #(assoc %1 %2 (inc (%1 %2 0)))
    {}
    (re-seq #"\w+" s))

; (This can also be done using the `frequencies` function.)

I dont understand this part: (inc (%1 %2 0))

like image 344
nenad Avatar asked Feb 13 '26 03:02

nenad


2 Answers

The first argument (%1 in the anonymous function) to the function passed to reduce is the accumulator, which is initally the empty map {} passed as the second argument to reduce. Maps are functions which lookup the value for the given key, returning the optional default if the key is not found e.g.

({"word" 1} "word") = 1

and

({"word" 1} "other" 0) = 0

so

(%1 %2 0)

looks up the count for the current word (second argument to the reducing function) in the accumulator map, returning 0 if the word has not been added yet. inc increments the current count, so

#(assoc %1 %2 (inc (%1 %2 0))

increments the count of the current word in the intermediate map, or sets it to 1 if this is the first time the word has been encountered.

like image 119
Lee Avatar answered Feb 15 '26 17:02

Lee


Here's an easier to read example of the same thing, not using anonymous function syntax:

(reduce
  (fn [acc elem]
    (assoc acc elem (inc (acc elem 0))))
  {}
  (re-seq #"\w+" "a dog a cat a dog a banana"))
=> {"a" 4, "dog" 2, "cat" 1, "banana" 1}

Here acc is the map we are building up, and elem is the current word. Let's break down (inc (acc elem 0)):

  1. inc is going to increment the number returned from the inner expression
  2. (acc elem 0) is going to get the current number from the acc map for the word elem, and if there is no number there it'll return 0. This is short for (get acc elem 0) -- maps are functions too and behave like the get function.

You can also achieve the same effect as (assoc acc elem (inc (acc elem 0))) with (update acc elem (fnil inc 0)).

The same logic applies when you replace the reduce function with an anonymous syntax using numbered arguments.

like image 29
Taylor Wood Avatar answered Feb 15 '26 16:02

Taylor Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!