用于破坏地图的Clojure快捷方式 [英] Clojure shortcuts for destructuring maps

查看:57
本文介绍了用于破坏地图的Clojure快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我正在学习使用快捷键:keys 来破坏地图时,这个问题才刚刚出现。

This question just came up for me as I was learning about using the shortcut :keys for destructuring a map.

假设我有以下地图:

(def my-hashmap {:a "A" :b "B" :c "C" :d "D"})

现在我可以参考写

(let [{first-key :a second-key :b} my-hashmap] 
    (println first-key second-key))

我得到 AB 。现在使用:keys 密钥必须与原始密钥相同(没有),否则clojure返回 nil ?因此,对于

and i get A B. Now using :keys the keys have to be the same as the original ones (without :), or otherwise clojure returns nil? So, for

(let [{:keys [first-key second-key]} my-hashmap] 
    (println first-key second-key))

您将得到 nil nil

我是不是看到了这个错误,或者确实是这种不合逻辑的事情发生在Clojure中,因为这两种方法都旨在引用键,因此应该以相同的方式工作?但是它们没有,因为如果我写(让[{:keys [a b]} my-hashmap](println a b)),我会再次得到正确的答案!

Am i seeing this wrong or is really this un-logical thing happening in clojure, because both methodes were meant to refer to the keys and thus should work in the same manner? But they don't, because if I write (let [{:keys [a b]} my-hashmap] (println a b)) I get again the right answer!

推荐答案

您在第二个示例中对:keys 的要求不能之所以会被满足,是因为无法推断出应该查找哪个键以将其值绑定到您正在使用的任意符号。

Your requirement to :keys in the second example can't be met because there is no way to deduce which individual keys should be looked up to have their values bound to the arbitrary symbols you are using.

请注意,地图是关联的,但不是有序的数据结构。因此,如果您希望使用其他名称,则需要将它们映射到名称和类型,就像在第一个示例中一样,可以在析构图中查看其值。

Notice that maps are associative, but not ordered data structures. Hence if you wish to use different names, they need to be mapped to the names and types their values can be looked up at in the destructored map, as you did in your first example.

您可以在地图中具有完全限定名称的:keys 向量中使用符号和关键字。此外,:syms :strs 可用于针对符号或字符串的键进行析构。

You can use both symbols and keywords in the :keys vector that have fully qualified names of keywords in the map. Futhermore, :syms and :strs are available to destructor against keys which are symbols or strings.

这篇关于用于破坏地图的Clojure快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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