我们经常通过测试散列映射来查找某个键的存在,例如:data ,通过测试该键对nil的值的试验检索,如
(defn test-my-hash-map [my-hash-map] (if (:data my-hash-map) 42 "plugh!"))对于任何包含key :data hash值的散列映射,其值都为42 , 除了值为nil 。
(map test-my-hash-map [{:data "Hello!"} ; ~~> 42 {:no-data "Yikes!"} ; ~~> "plugh!" {:data nil} ; ~~> "plugh!", but I need it to say 42 :( ])我根本没有办法做到这一点,而这正在搞乱一些数据处理场景,我们从非Clojure源获取数据,其中缺少的密钥意味着“我在该密钥处没有数据”以及键值nil意味着“我在那里有数据,但无论出于何种原因,我都无法给你。” 我没有看到用Clojure代码区分这些情况的方法。 我非常谦虚的解决方法是插入一个Java Shim,检测差异并在交给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.
最满意答案
有一个clojure函数可以提供默认值。
(:foo {:bar 1}) ; ==> nil (get {:bar 1} :foo "no key inserted") ; ==> "no key inserted"当然还contains? 。
(contains? {:bar 1} :bar) ; ==> trueThere'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更多推荐
发布评论