从地图中删除nil值

从地图中删除nil值

本文介绍了从地图中删除nil值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Clojure地图,可能包含的值是nil,我试图写一个函数来删除它们,没有多少成功(我是新的)。



例如:

 (def record {:a 1:b 2:c nil})
(merge(for [[kv] record:when(not(nil?v))] {kv}))


$ b b

这导致一系列映射,这不是我期望的合并:

  1} {:b 2})

我想要:

  {:a 1,:b 2} 


列表推导返回一个地图列表,所以您需要将此列表作为可选参数应用到合并函数:

  user> (apply [for [[kv] record:when(not(nil?v))] {kv}))
{:b 2,:a 1}

通过将地图过滤为序列并结合到地图中,可获得更简洁的解决方案:

  user> (into {}(filter second record))
{:a 1,:b 2}

不要移除 false 值:

  (into {}(remove(comp nil?second)record))
{:a 1,:b false}

使用 dissoc 允许永久性数据共享,而不是创建一个新的地图:

  user> (apply dissoc 
record
([[kv] record:when(nil?v)] k))
{:a 1,:b 2}


I have a Clojure map that may contain values that are nil and I'm trying to write a function to remove them, without much success (I'm new to this).

E.g.:

(def record {:a 1 :b 2 :c nil})
(merge (for [[k v] record :when (not (nil? v))] {k v}))

This results in a sequence of maps, which isn't what I expected from merge:

({:a 1} {:b 2})

I would like to have:

{:a 1, :b 2}
解决方案

your for list comprehension returns a LIST of maps, so you need to APPLY this list to the merge function as optional arguments:

user> (apply merge (for [[k v] record :when (not (nil? v))] {k v}))
{:b 2, :a 1}

More concise solution by filtering the map as a sequence and conjoining into a map:

user> (into {} (filter second record))
{:a 1, :b 2}

Dont remove false values:

user> (into {} (remove (comp nil? second) record))
{:a 1, :b false}

Using dissoc to allow persistent data sharing instead of creating a whole new map:

user> (apply dissoc
       record
       (for [[k v] record :when (nil? v)] k))
{:a 1, :b 2}

这篇关于从地图中删除nil值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 14:51