Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Destructuring map function arguments in clojure: does the map need to go last?

I’m trying to define a function that takes a map and a regular argument, and I’d like to destructure parts of the map, something like

(defn do-stuff
  [[{:keys [foo bar]} where] what]
  (println foo bar what))

but when I call the function I get an error

; Execution error (UnsupportedOperationException) at .../do-stuff (REPL:34).
; nth not supported on this type: PersistentArrayMap

If I swap function arguments

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(defn do-stuff
  [what [{:keys [foo bar]} where]]
  (println foo bar what))

everything works fine. Of course I could just write a let inside the function and do the destructuring there, but I wonder what I’m missing…

EDIT: to clarify I expect to be able to call the function like

(do-stuff {:foo "something" :bar "something else"} "baz")

>Solution :

Since you fail to show us, what your call there is, my guess is, that
you are confusing the let syntax for destructuring with the one on
functions.

So the following calls work – note the nesting in a vector of the map
and the dangling where:

(defn do-stuff
  [[{:keys [foo bar]} where] what]
  (println foo bar what))

(do-stuff [{:foo 1 :bar 2} 3] 4)
; 1 2 4

(defn do-stuff
  [what [{:keys [foo bar]} where]]
  (println foo bar what))

(do-stuff 0 [{:foo 1 :bar 2} 3])
; 1 2 0

Since you don’t print where, it seems like you want to hold on to the
map itself. But this is done via :as.

(defn do-stuff
  [{:keys [foo bar] :as where} what]
  (println foo bar where what))

(do-stuff {:foo 1 :bar 2 :baz 3} 4)
; 1 2 {:foo 1, :bar 2, :baz 3} 4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading