Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapping a clojure map

I've been experimenting with the map function in Clojure and was wondering, what is the best practice of applying map to a map collection so that:

(map #(pprint (str %1 " " %2)) {:hello 1 :world 2})

outputs (the order doesn't really matter now):

:hello 1
:world 2

My fist idea was:

(def my-map {:hello 1 :world 2})
(map #(pprint (str %1 " " %2)) (keys my-map) (vals my-map))

But! I haven't found any evidence in documentation that Clojure (or e.g. ClojureScript) guaranties that the order of keys and vals sequences is mutually preserved.

Another idea was:

(map #(pprint (str (first %1) " " (rest %1))) my-map)

Which is not that nice as it would be with plain %1 and %2.

I believe that there a better way to do this. Can you please share, if you know it? Thanks in advance!

like image 934
Zaur Nasibov Avatar asked Dec 05 '25 07:12

Zaur Nasibov


1 Answers

keys and vals do give the same order.

Alternatively, you could map a function across the entries of the map:

(map (fn [[k v]] ...) {:foo 1 :bar 2})

Or use reduce-kv:

(reduce-kv (fn [_ k v] ...) nil {:foo 1 :bar 2})
like image 100
Michał Marczyk Avatar answered Dec 07 '25 17:12

Michał Marczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!