Filter nil values from Clojure map?

后端 未结 5 2119
遥遥无期
遥遥无期 2021-02-12 14:42

What is the best way to filter nil values from a Clojure map {}?

{ :a :x :b nil :c :z }
;;=>  { :a :x, :c :z }
相关标签:
5条回答
  • 2021-02-12 15:18

    The nicest way of doing this is actually(into {} (keep second {:a :x :b nil}))

    0 讨论(0)
  • 2021-02-12 15:19

    Probably not the best solution, but here's one that uses list comprehension:

    (into {} 
      (for [[k v] {:a 1 :b nil :c :z} :when (not (nil? v))]
        [k v]))
    
    0 讨论(0)
  • 2021-02-12 15:20

    I would use:

    (into {} (filter (comp some? val) {:a :x, :b nil, :c :z}))
    
    => {:a :x, :c :z}
    

    Doing the some? check explicitly is important because if you just do (into {} (filter val {...})) then you will erroneously remove values that are boolean false.

    0 讨论(0)
  • 2021-02-12 15:20

    I use following code:

    (into {} (filter val {:a 1, :b 2, :c nil}))
    ;;=> {:a 1, :b 2}
    

    NOTE: this will remove false values as well as nils

    0 讨论(0)
  • 2021-02-12 15:29
    (into {} (keep (fn [e] (if (val e) e)) {:a :x :b nil :c :z}))
    ;;=> {:a :x, :c :z}
    

    or a little shorter:

    (into {} (keep #(if (val %) %) {:a :x :b nil :c :z}))
    

    In fact, your filter suggestion is much better and shorter, so I would just use that:

    (into {} (filter val {:a :x :b nil :c :z}))
    
    0 讨论(0)
提交回复
热议问题