1

Can anyone explain me this function definition line of clojure

 (defn insert [{:keys [el left right] :as tree} value] 
      (**something**))

2 Answers 2

3

The insert function is using destructuring for maps, retrieving values from keys. I think the below would make this clearer:

(defn insert [{:keys [el left right] :as tree} value]
      (println (str el " " left " " right))
      (println "-")
      (println tree)
      (println "-")
      (println value)   )


(def mytree  {:el "el" :left "left" :right "right"})

(insert mytree 3)
Sign up to request clarification or add additional context in comments.

2 Comments

But why we have :keys here? Cant we just pass a deftype and use it
You could do that or you could also just pass a map, but if your data is just tree-like enough that you want to use this function and you don't want to make it into records then I'm pretty sure defining the function like this leaves it more generic/reusable.
2

This is argument destructuring in Clojure. You can read more about it here: https://gist.github.com/john2x/e1dca953548bfdfb9844

{:keys [el left right]} assumes the first argument (we'll call it arg) is a map and binds (:el arg) to el, (:left arg) to left and (:right arg) to right for the scope of the function.

{:keys [.. .. ..]} :as tree} binds arg to tree.

Then value is handled normally, without any desctructuring.

Comments

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.