如何区分Clojure中值为零的密钥中缺失的密钥?(How to distinguish a missing key from a key with value nil in Clojure?)

编程入门 行业动态 更新时间:2024-10-22 12:31:38
如何区分Clojure中值为零的密钥中缺失的密钥?(How to distinguish a missing key from a key with value nil in Clojure?)

我们经常通过测试散列映射来查找某个键的存在,例如: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) ; ==> true

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

更多推荐

本文发布于:2023-07-14 20:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107253.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密钥   中值   缺失   为零   Clojure

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!