We are often testing hash-maps for the presence of a certain key, say :data
, by testing a trial retrieval of that key's value against nil
, as in
(defn test-my-hash-map [my-hash-map]
(if (:data my-hash-map) 42 "plugh!"))
This produces 42
for any hash-map that contains the key :data
with any value, except the value nil
.
(map test-my-hash-map
[{:data "Hello!"} ; ~~> 42
{:no-data "Yikes!"} ; ~~> "plugh!"
{:data nil} ; ~~> "plugh!", but I need it to say 42 :(
])
I don't see any way to do it at all, and this is messing up some data processing scenarios where we're getting data from non-Clojure sources in which a missing key means "I have no data at that key" and a key with a nil
value means "I have data there, but I can't give it to you for whatever reason." I don't see a way to distinguish these cases in Clojure code.
My extremely yucchy work-around is to insert a Java shim that detects the differences and inserts extra columns (keys) for the special cases before handing off to Clojure.
There's a clojure function get
that allows a default value to be supplied.
(:foo {:bar 1}) ; ==> nil
(get {:bar 1} :foo "no key inserted") ; ==> "no key inserted"
Of course there's also contains?
.
(contains? {:bar 1} :bar) ; ==> true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With