在 Clojure 中,如何解构映射的所有键?
在 clojure 中,可以像这样解构映射的某些键:
(let [{:keys [cpp js]} {:cpp 88 :js 90}]
(println js); 90
(println cpp); 88
)
Is there a way to destruct all the key of a map?
也许是这样的:
(let [{:all-the-keys} {:cpp 88 :js 90}]
(println js); 90
(println cpp); 88
)
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
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
事实并非如此,而且这也不是一个好主意。想象一下:
foo 和 bar 是全局变量吗?当地人?您应该从 m 中提取密钥吗?如果 m 有时 包含 foo 键,并且 foo 也是一个全局函数,那么这段代码应该做什么?有时调用全局,有时调用m中存储的函数?
忽略技术问题(可以克服),这对于可读性和可预测性来说确实是一场灾难。只需明确您想要拔出哪些钥匙即可;如果您经常想要取出相同的十个键,您可以编写一个简单的宏,例如
(with-person p body)
来简化您的常见情况。Not really, and it wouldn't be a good idea. Imagine:
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 (which could 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.这个问题已经很老了,所以你可能已经忘记了,但是当我尝试做同样的事情时,它出现在谷歌上,所以如果我发布我的解决方案,它可能会帮助其他人。
这基本上将映射
{:cpp 88 :js 90}
转换为绑定形式[cpp 88 js 90]
然后构造一个let
绑定,并执行一些 eval-jitsu 以确保这种情况在运行时发生。This question is pretty old so you've probably forgotten about it, but it came up on google when I was trying to do the same thing, so if I post my solution it might help someone else out.
This basically transforms the map
{:cpp 88 :js 90}
into the binding form[cpp 88 js 90]
then constructs alet
binding, along with performing some eval-jitsu to make sure that this happens at run time.您可以编写一个宏来执行此操作(有效地创建迷你 DSL),但我认为这不是一个好主意,原因如下:
我建议在您的情况下使用简单的 doseq循环地图:
请注意:
k
和值v
You could write a macro to do this (effectively creating a mini-DSL), but I don't think it is a very good idea for the following reasons:
I'd recommend just using a simple doseq in your case to loop over the map:
Note that:
k
and valuev
from each map entry