在Clojure中有条件地初始化映射的元素 [英] Initializing elements of a map conditionally in Clojure

查看:126
本文介绍了在Clojure中有条件地初始化映射的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有条件避免在初始化/定义时向地图添加元素的最佳方法。在这种情况下,如果键的值为nil,我想避免向地图添加元素。

I'm looking for the best way to conditionally avoid adding an element to a map when it is being initialized/defined. In this case, I want to avoid adding an element to a map if the value for the key is nil.

(defn create-record [data]
  (let [res {
    :username (data :username)
    :first-name (get-in data [:user-info :name :first])
    :last-name (get-in data [:user-info :name :last])
    :gender (get-in data [:user-info :sex])
   }])
)

我不想在地图中添加性别get-in是nil(数据中的sex字段不存在)。有没有办法做到这一点,当我创建地图?我可以删除所有的值,其值为nil在我创建地图后,但在某些情况下,我想要一些键有nil值和其他人不在地图中,如果他们将有nil值。

I don't want to add gender to the map if the results of the get-in are nil (the sex field in the data does not exist). Is there a way to do this when I create the map? I could remove all keys whose value is nil after I create the map but, in some cases, I want some keys to have nil values and others to not be in the map at all if they would have nil values.

推荐答案

我会使用 merge

I would use a combination of merge and when-let for these optional parameters.

核心思想是合并单个元素映射或每个可选参数的nil。合并为nil将不会执行任何操作,因此您不会在地图中看到nil。

The core idea is to merge in either a single element map or nil for each of the optional parameters. Merging in nil will do nothing, so you won't see the nil in the map.

(defn create-record [data]
  (let [res (merge {:username (data :username)
                    :first-name (get-in data [:user-info :name :first])
                    :last-name (get-in data [:user-info :name :last])}
                   (when-let [gender (get-in data [:user-info :sex])]
                     {:gender gender}))]
    res))

,我建议写一个简短的宏或函数来保持代码更简洁。

Depending on how frequently you need to do this, I would recommend writing a short macro or function around the when-let to keep the code more concise.

这篇关于在Clojure中有条件地初始化映射的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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