murtaza52
murtaza52

Reputation: 47451

how to destructure a map as key and value

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

Upvotes: 7

Views: 5979

Answers (3)

BillRobertson42
BillRobertson42

Reputation: 12883

There are shortcuts available for destructuring maps. For example, if you're looking for specific keys, then you don't have to type out name1 :key1 name1 :key2...

e.g.

main=> (defn fbb [{:keys [foo bar baz]}] (+ foo bar baz))
#'main/fbb
main=> (fbb {:foo 2 :bar 3 :baz 4}) 
9

instead of...

(defn fbb [{foo :foo bar :bar baz :baz}] (+ foo bar baz))

If your map keys are strings, you can say :strs instead of :keys and if they are symbols you can use :syms.

Upvotes: 2

runexec
runexec

Reputation: 862

user=> (for [x (hash-map :a 1 :b 2 :c 3)] (str (first x) " " (second x)))
(":a 1" ":c 3" ":b 2")

Upvotes: -3

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91617

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.

Upvotes: 19

Related Questions