1

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
  • 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. Commented Nov 2, 2019 at 8:22

1 Answer 1

6

[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

Sign up to request clarification or add additional context in comments.

1 Comment

Slightly more accurate: second one should be a sequential type, Its first element will bind to key, its second to value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.