在Clojure中,如何解构映射的所有键? [英] In Clojure, how to destructure all the keys of a map?
问题描述
(let [{:keys [ cpp js]} {:cpp 88:js 90}]
/ pre>
(println js); 90
(println cpp); 88
)
是否有办法重组所有地图的键?
也许像:
(let [{:all-the-keys} {:cpp 88:js 90}
(println js); 90
(println cpp); 88
)
解决方案不是真的,这不是一个好主意。想象:
(let [{:all-the-keys} m]
(foo bar))
是foo还是bar全局变量?当地人?你应该从m中提取的密钥?如果有时包含foo键,此代码应该做什么,foo也是一个全局函数?有时你调用全局的,有时你调用函数存储在m?
忽略技术问题(大部分可能被克服),这真的是一个灾难用于可读性和可预测性。只要明确你想要拉出什么键;如果你经常想拉出相同的十个键,你可以写一个简单的宏,如
(with-person p body)
,这样就简化了这种情况。In clojure, it is possible to destructure some keys of a map like this:
(let [{:keys [cpp js]} {:cpp 88 :js 90}] (println js); 90 (println cpp); 88 )
Is there a way to destructure all the keys of a map?
Maybe something like:
(let [{:all-the-keys} {:cpp 88 :js 90}] (println js); 90 (println cpp); 88 )
解决方案Not really, and it wouldn't be a good idea. Imagine:
(let [{:all-the-keys} m] (foo bar))
Are foo and bar globals? Locals? Keys you should extract from m? What should this code do if m sometimes contains a foo key, and foo is also a global function? Sometimes you call the global, and sometimes you call the function stored in m?
Ignoring the technical problems (most of which can probably be overcome), it is really a disaster for readability and predictability. Just be explicit about what keys you want to pull out; if you frequently want to pull out the same ten keys, you can write a simple macro like
(with-person p body)
that simplifies that common case for you.这篇关于在Clojure中,如何解构映射的所有键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!