Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to destructure a map as key and value

Tags:

clojure

Is there a way to destructure a key value pair ? I have a function which take a map as a parameter, I would like to extract the value of both the key and the value in the params itself. How do I do that ?

I can do the following with a vector -

((fn [[a b]] (str a b)) [a b])

How do I do the same / similar with map -

((fn[{k v}] (str k v)) {k v})

Thanks, Murtaza

like image 630
murtaza52 Avatar asked Sep 20 '12 03:09

murtaza52


1 Answers

map destructuring in functions arg lists is designed for extracting certain keys from a map and giving them names like so:

core> (defn foo [{my-a :a my-b :b}] {my-a my-b})
core/foo                                                                                     
core> (foo {:a 1 :b 2})
{1 2}

i recommend this tutorial. It is a little hard to give a direct equivalent to ((fn[{k v}] (str k v)) {k v}) because the map could have many keys and many values so the destructuring code would be unable to tell which key and value you where looking for. Destructuring by key is easier to reason about.

If you want to arbitrarily choose the first entry in the map you can extract it and use the list destructuring form on a single map entry:

core> (defn foo [[k v]] {v k})
#'core/foo                                                                                     
core> (foo (first {1 2}))
{2 1}   

in this example the list destructuring form [k v] is used because first returns the first map entry as a vector.

like image 101
Arthur Ulfeldt Avatar answered Sep 30 '22 22:09

Arthur Ulfeldt