Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Clojure's map destructuring look reversed?

Tags:

clojure

Destructuring a map looks reversed to me. Can anybody explain what is happening?

I expect that this is the right form of destructuring a map

;=> (let [{:a a :b b} {:a 1 :b 2}] [a b])

which returns Exception Unsupported binding form: :a clojure.core/destructure/pb--4541 (core.clj:4029). Clojure documentations say that below is the right way. But it looks that keys and values are reversed.

This should be the right way:

;=> (let [{a :a b :b} {:a 1 :b 2}] [a b]) [1 2]

What is happening when destructuring a map?

like image 699
taro Avatar asked Mar 28 '26 09:03

taro


1 Answers

It is not really reversed, actually it makes sense. It says: bind to symbol 'a' to value that is associated with the keyword :a

Are you aware of this when your map uses keywords as keys?

(let [{:keys [a b]} {:a 1 :b 2}] [a b])

Much neater and elegant!

Other variants exist if your keys are symbols or strings.

like image 68
Chiron Avatar answered Apr 02 '26 20:04

Chiron