Clojure让绑定表单 [英] Clojure let binding forms

查看:158
本文介绍了Clojure让绑定表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解如何让绑定在关闭地图工作。从我的理解let后面跟一个向量,其中第一个项目是我想要绑定的符号,后面是我想要绑定的值。

I'm trying to understand how let bindings work in closure in regards to maps. From my understanding let is followed by a vector where the first item is the symbol I want bound, followed by the value I want to bind it to. So

(let [a 1 b 2] a) 

会给出值1。

所以如果我声明映射如

(def people {:firstName "John" :lastName "Doe"})

而我想绑定键firstName,这将是一个简单的Hello Person的正确形式

And I want to bind the key firstName then this would be the correct form for a simple "Hello Person"

(let [personName (:firstName people)] (str "hello " personName))


b $ b

这在Clojure的网站上有效,但是在 http://clojure.org/special_forms#binding

This works, however on the Clojure website http://clojure.org/special_forms#binding-forms they show a different form which also works

(let [{personName :firstName} people] (str "hello " personName))

这两个代码段都可以正常工作, m混淆了第二个语法。这只是语法糖还是重复的工作方式,是比另一个更惯用的吗?

Both code snippets work and I understand why the first version works but I'm confused on the syntax on the second. Is this just syntactical sugar or a duplicate way of working and is one more idiomatic than the other?

推荐答案

最后一种形式是地图绑定解构。如果你想将多个变量绑定到同一个地图的不同元素,这是最有用的:

The last form is Map binding destructuring. It's most useful if you want to bind multiple variables to different elements of the same map:

(let [{firstName :firstName lastName :lastName address :address} people]
    (str "hello " firstName " " lastName ", I see you live at " address))

如果你使用以前的语法写出来,它将是:

If you were to write this out using the previous syntax, it would be:

(let [firstName (:firstName people) lastName (:lastName people) address (:address people)]
    (str "hello " firstName " " lastName ", I see you live at " address))

如您所见,这可以避免您重复在每个绑定。如果地图是计算的结果,它避免了必须绑定一个变量,所以你可以重复它。

As you see, this saves you from having to repeat people in each binding. And if the map is the result of a computation, it avoids having to bind a variable to that so you can repeat it.

解构也允许你布局绑定构造的格式与您访问的数据结构类似。这使得它对于复杂的结构更加惯用。

Destructuring also allows you to lay out the binding construct in a format that's similar to the data structure you're accessing. This makes it more idiomatic for complex structures.

这篇关于Clojure让绑定表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆