在 Clojure 的嵌套映射中关联多个键/值的惯用方法是什么?
想象一下您有一个这样的地图:
(def person {
:name {
:first-name "John"
:middle-name "Michael"
:last-name "Smith" }})
在一个表达式中更改与 :first-name 和 :last-name 关联的值的惯用方法是什么?
(澄清:假设您想将 :first-name 设置为“Bob”,将 :last-name 设置为“Doe”。我们还假设此映射中还有一些我们想要保留的其他值,因此从头开始构建它不是一个选项)
Imagine you have a map like this:
(def person {
:name {
:first-name "John"
:middle-name "Michael"
:last-name "Smith" }})
What is the idiomatic way to change values associated with both :first-name and :last-name in one expression?
(Clarification: Let's say you want to set :first-name to "Bob" and :last-name to "Doe". Let's also say that this map has some other values in it that we want to preserve, so constructing it from scratch is not an option)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有几种方法。
编辑
update-in
在地图上执行递归assoc
。在这种情况下,它大致相当于:当您深入一系列嵌套映射时,键的重复变得越来越乏味。
update-in
的递归可以让您避免一遍又一遍地重复键(例如:name
);递归调用之间的中间结果存储在堆栈中。查看 update-in 的源代码,了解它是如何完成的。assoc
是动态的(update-in
、assoc-in
以及大多数其他对 Clojure 数据结构进行操作的 Clojure 函数也是如此)。如果assoc
到地图上,它会返回一个地图。如果您assoc
到一个向量上,它会返回一个向量。查看 assoc 的源代码并查看RT.java< /code> Clojure 源代码中的详细信息。
Here are a couple of ways.
Edit
update-in
does recursiveassoc
s on your map. In this case it's roughly equivalent to:The repetition of keys becomes more and more tedious as you go deeper into a series of nested maps.
update-in
's recursion lets you avoid repeating keys (e.g.:name
) over and over; intermediary results are stored on the stack between recursive calls. Take a look at the source for update-in to see how it's done.assoc
is dynamic (as areupdate-in
,assoc-in
, and most other Clojure functions that operate on Clojure data structures). Ifassoc
onto a map, it returns a map. If youassoc
onto a vector, it returns a vector. Look at the source for assoc and take a look in inRT.java
in the Clojure source for details.我不确定我的情况是否完全相同,但我有要应用的更改列表:
在这种情况下,您可以使用 assoc-in 减少该列表,如下所示:
I'm not sure if my case is quite the same but I had list of changes to apply:
In that case you can reduce over that list with assoc-in like this: