开发者

Convert an array of tuples into a hash-map in Clojure

开发者 https://www.devze.com 2023-01-27 16:53 出处:网络
I have an array of tuples, where each tuple is a 2 t开发者_如何学Gouple with a key and a value. What would be the cleanest way to convert this array of tuples into a hash-map?user=> (into {} [[:a 1

I have an array of tuples, where each tuple is a 2 t开发者_如何学Gouple with a key and a value. What would be the cleanest way to convert this array of tuples into a hash-map?


user=> (into {} [[:a 1] [:b 2]])
{:a 1, :b 2}


A map is a sequence of MapEntry elements. Each MapEntry is a vector of a key and value. The tuples in the question are already in the form of a MapEntry, which makes things convenient. (That's also why the into solution is a good one.)

user=> (reduce conj {} [[:a 1] [:b 2]])
{:b 2, :a 1}


Assuming that "tupel" means "two-elememt array":

(reduce 
  (fn [m tupel] 
      (assoc m 
            (aget tupel 0) 
            (aget tupel 1))) 
  {} 
  array-of-tupels)


user=> (def a [[:a 4] [:b 6]])
user=> (apply hash-map (flatten a))
{:a 4, :b 6}
0

精彩评论

暂无评论...
验证码 换一张
取 消