在 Clojure 中,如何解构地图的所有键? [英] In Clojure, how to destructure all the keys of a map?

查看:21
本文介绍了在 Clojure 中,如何解构地图的所有键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 clojure 中,可以像这样解构映射的某些键:

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?

也许是这样的:

(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))

foo 和 bar 是全局变量吗?当地人?您应该从 m 中提取的键?如果 m sometimes 包含一个 foo 键,并且 foo 也是一个全局函数,这段代码应该怎么做?有时调用全局,有时调用m中存储的函数?

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?

忽略技术问题(可以克服),这对于可读性和可预测性来说真的是一场灾难.只需明确说明您要拔出哪些键即可;如果您经常想拔出相同的十个键,您可以编写一个简单的宏,例如 (with-person p body) 来为您简化这种常见情况.

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.

这篇关于在 Clojure 中,如何解构地图的所有键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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