Reputation: 2319
As I understand it, the let
keyword, locally binds variables to values (supporting some sort of pattern matching). It receives two arguments. First is a vector with the symbol we want to bind and the value we want bound. Then comes an expression that uses that value.
In this example, first the variable person
is defined:
user=> (def person {:name "Jabba" :profession "Gangster"})
#'user/person
now suppose we want to destruct the map using the let
function:
user=> (let [{name :name} person] (str "The person's name is " name))
"The person's name is Jabba"
Why is it that in [{name :name} person]
, :name
should necessarily appear after the variable name
? This actually wouldn't work:
user=> (let [{:name name} person] (str "The person's name is " name))
"The person's name is "
Why is the order like this? I thought that maps could be defined in either order:
user=> (def map1 {:a 1})
#'user/map1
user=> (def map2 {1 :a})
#'user/map2
Upvotes: 0
Views: 237
Reputation: 1788
in a map, ordering of entry values is VERY IMPORTANT; first guy is key, second is value.
if you don't like to repeat yourself, you can use below syntax to destructure one or more entries in a map:
(let [{:keys [name profession]} person] (str "The person's name is " name ", and job is " profession))
Upvotes: 1
Reputation: 101162
I thought that maps could be defined in either order:
user=> (def map1 {:a 1})
#'user/map1
user=> (def map2 {1 :a})
#'user/map2
No.
map1
has one element; with the key :a
and the value 1
.
map2
has one element; with the key 1
and the value :a
.
It's not the same.
Upvotes: 1