简体   繁体   English

销毁地图(使用let关键字)

[英]Destructing a map (using the let keyword)

As I understand it, the let keyword, locally binds variables to values (supporting some sort of pattern matching). 据我了解, let关键字在本地将变量绑定到值(支持某种模式匹配)。 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: 在此示例中,首先定义变量person

user=> (def person {:name "Jabba" :profession "Gangster"})
#'user/person

now suppose we want to destruct the map using the let function: 现在假设我们要使用let函数破坏地图:

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 ? 为什么在[{name :name} person]:name必须出现在变量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

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; map1有一个元素; with the key :a and the value 1 . 使用键:a和值1
map2 has one element; map2有一个元素; with the key 1 and the value :a . 使用键1和值:a

It's not the same. 这是不一样的。

  1. in a map, ordering of entry values is VERY IMPORTANT; 在映射中,输入值的顺序非常重要; first guy is key, second is value. 第一个人是关键,第二是价值。
  2. 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM