Clojure get map key by value

前端 未结 3 1759
失恋的感觉
失恋的感觉 2020-12-31 11:58

I\'m a new clojure programmer.

Given...

{:foo \"bar\"}

Is there a way to retrieve the name of the key with a value \"bar\"?

3条回答
  •  借酒劲吻你
    2020-12-31 12:50

    There can be multiple key/value pairs with value "bar". The values are not hashed for lookup, contrarily to their keys. Depending on what you want to achieve, you can look up the key with a linear algorithm like:

    (def hm {:foo "bar"})
    (keep #(when (= (val %) "bar")
              (key %)) hm)
    

    Or

    (filter (comp #{"bar"} hm) (keys hm))
    

    Or

    (reduce-kv (fn [acc k v]
                 (if (= v "bar")
                   (conj acc k)
                   acc))
               #{} hm)
    

    which will return a seq of keys. If you know that your vals are distinct from each other, you can also create a reverse-lookup hash-map with

    (clojure.set/map-invert hm)
    

提交回复
热议问题