简体   繁体   中英

Get key by first element in value list in Clojure

This is similar to Clojure get map key by value

However, there is one difference. How would you do the same thing if hm is like

{1 ["bar" "choco"]}

The idea being to get 1 (the key) where the first element if the value list is "bar"? Please feel free to close/merge this question if some other question answers it.

I tried something like this, but it doesn't work.

(def hm {:foo ["bar", "choco"]})

(keep #(when (= ((nth val 0) %) "bar")
         (key %))
      hm)

You can filter the map and return the first element of the first item in the resulting sequence:

(ffirst (filter (fn [[k [v & _]]] (= "bar" v)) hm))

you can destructure the vector value to access the second and/or third elements eg

(ffirst (filter (fn [[k [f s t & _]]] (= "choco" s)) 
                {:foo ["bar", "choco"]}))

past the first few elements you will probably find nth more readable.

Another way to do it using some :

(some (fn [[k [v & _]]] (when (= "bar" v) k)) hm)

Your example was pretty close to working, with some minor changes:

(keep #(when (= (nth (val %) 0) "bar")
         (key %))
       hm)

keep and some are similar, but some only returns one result.

in addition to all the above (correct) answers, you could also want to reindex your map to desired form, especially if the search operation is called quite frequently and the the initial map is rather big, this would allow you to decrease the search complexity from linear to constant:

(defn map-invert+ [kfn vfn data]
  (reduce (fn [acc entry] (assoc acc (kfn entry) (vfn entry)))
          {} data))

user> (def data
        {1 ["bar" "choco"]
         2 ["some" "thing"]})
#'user/data

user> (def inverted (map-invert+ (comp first val) key data))
#'user/inverted

user> inverted
;;=> {"bar" 1, "some" 2}

user> (inverted "bar")
;;=> 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM