本文介绍了Clojure:如果键存在,惯用更新地图的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 这里是我的问题:我想要一个函数 helpme 获取一个映射并替换键:r code>:g 使用空向量,当且仅当这些键存在。例如:Here's my problem: I want a function helpme that takes a map and replaces the keys :r and :g with empty vectors if and only if those keys exist. For example:输入:(helpme {:a "1" :r ["1" "2" "3"] :g ["4" "5"]})输出:{:a "1" :r [] :g []} $ b Input:(helpme {:a "1" :r ["1" "2" "3"]})输出:{:a "1" :r []} 我可以定义一个函数helpme来做到这一点,但它过于复杂,我觉得必须有一个更容易(更习惯)的方式... I can define a function "helpme" that does this, but it's overly complicated, and I feel like there must be an easier (more idiomatic) way...这里是我做过的过于复杂的方式,如下所示:Here's the overly complicated way I've done, as requested below:(defn c [new-doc k] (if (contains? new-doc k) (assoc new-doc k []) new-doc))(defn helpme [new-doc] (c (c new-doc :r) :g)) 推荐答案 (defn helpme [m] (into m (for [[k _] (select-keys m [:r :g])] [k []])))短,只需要在一个位置编辑项目数量设置为 [] 更改。 Short, and only requires editing in one place when the number of items to set to [] changes. 这篇关于Clojure:如果键存在,惯用更新地图的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-17 01:11