Welcome! Please see the About page for a little more info on how this works.

+5 votes
ago in Clojure by
edited ago by

On latest Clojure alpha, we added :keys! (and :syms!/:strs!) check for key presence. They do not check the value (by design). So a map can have the key, with a nil value, and still pass the check:

(let [{:keys! [a]} {:a nil}]
  a)
;; => nil

Sometimes nil is not a valid value for a given key. In those cases, a programmer may want to avoid adding the key at all, rather than adding it with nil. This is the most common idiom today:

(cond-> m
  (some? v) (assoc k v))

A dedicated assoc-some function would help. It skips the key when the value is nil:

(assoc-some {:a 1} :b 2)
;; => {:a 1 :b 2}

(assoc-some {:a 1} :b false)
;; => {:a 1 :b false}

(assoc-some {:a 1} :b nil :c nil)
;; => {:a 1}

1 Answer

0 votes
ago by

You could just use Medley: it's very lightweight.

https://github.com/weavejester/medley

It has a lot of useful functions, and it's cross-platform.

...