1
votes

I'm getting my feet wet with Clojure the past couple of day and came across this piece of code:

(defn reduce-example
  [new-map [key val]]
  (assoc new-map key (inc val)))

(reduce reduce-example
        {}
        {:max 30 :min 10})
; => {:max 31, :min 11}

I am confused about the function argument in reduce-example, more specifically this: new-map [key value]

From what I studied so far and after the function name, you can declare the number of arguments (arities). For example [x y z], but what does [new-map [key value]] mean? of course it can extract the key and value but how? how should I interpret this function argument?

Thank you

1
Have a look at clojure.org/guides/destructuring#_sequential_destructuring ; the [key value] takes a parameter which is a sequence and assigns the first value to key and the second to value. Also note that when passing a map to a function like reduce, it is automatically converted into a sequence of vectors. Try (seq {:max 30 :min 30}) and you'll see what I mean. This also shows you where the [key value] that is being passed into reduce-example is coming from. - optevo

1 Answers

6
votes

[new-map [key value]] mean the function expect two argument:

  • first one will bind to name new-map

  • second one (should be a sequential type with 2 elements inside) . The elements inside will bind to key and value

Clojure has an ability of destructuring