Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish a missing key from a key with value nil in Clojure?

Tags:

clojure

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.

like image 853
Reb.Cabin Avatar asked Mar 23 '23 08:03

Reb.Cabin


1 Answers

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
like image 180
Daniel Gratzer Avatar answered Apr 28 '23 06:04

Daniel Gratzer