我是一个新的clojure程序员.
鉴于...
{:foo "bar"}
Run Code Online (Sandbox Code Playgroud)
有没有办法检索值为"bar"的键的名称?
我查看了地图文档,可以看到一种方法来检索键和值,或只是值,但不仅仅是键.帮助赞赏!
Leo*_*hin 24
可以有多个键值/值对,其值为"bar".对于查找,不会对值进行哈希处理,与其键相反.根据您想要实现的目标,您可以使用线性算法查找密钥,例如:
(def hm {:foo "bar"})
(keep #(when (= (val %) "bar")
(key %)) hm)
Run Code Online (Sandbox Code Playgroud)
要么
(filter (comp #{"bar"} hm) (keys hm))
Run Code Online (Sandbox Code Playgroud)
要么
(reduce-kv (fn [acc k v]
(if (= v "bar")
(conj acc k)
acc))
#{} hm)
Run Code Online (Sandbox Code Playgroud)
这将返回一系列密钥.如果您知道您的val彼此不同,您还可以创建一个反向查找哈希映射
(clojure.set/map-invert hm)
Run Code Online (Sandbox Code Playgroud)
user> (->> {:a "bar" :b "foo" :c "bar" :d "baz"} ; initial map
(group-by val) ; sorted into a new map based on value of each key
(#(get % "bar")) ; extract the entries that had value "bar"
(map key)) ; get the keys that had value bar
(:a :c)
Run Code Online (Sandbox Code Playgroud)