swap keys and values in a map

后端 未结 4 1058
忘掉有多难
忘掉有多难 2021-02-19 01:47

Is there a function to swap the key and value of a given map. So given a map, I want the keys to become values, and values the keys.

(swap {:a 2 b 4}) => {2 :         


        
4条回答
  •  终归单人心
    2021-02-19 02:13

    Here is an option that may fit the problem using reduce:

    (reduce #(assoc %1 (second %2) (first %2)) {} {:a 2 :b 4})
    

    Here in a function

    (defn invert [map]
      (reduce #(assoc %1 (second %2) (first %2)) {} map))
    

    Calling

    (invert {:a 2 b: 4})
    

    Then there is the reduce-kv (cleaner in my opinion)

    (reduce-kv #(assoc %1 %3 %2) {} {:a 2 :b 4})
    

提交回复
热议问题