Reputation: 1267
In Clojure, I want to both rename-keys and select-keys from a map. The simple way of doing is with:
(-> m
(rename-keys new-names)
(select-keys (vals new-names)))
But this will itetate over the entire map twice. Is there a way to do it with one iteration?
Upvotes: 4
Views: 988
Reputation: 51490
Sure, there is a way to do it with a single iteration.
You could do it using reduce-kv
function:
(reduce-kv #(assoc %1 %3 (get m %2)) {} new-names)
or just a for loop:
(into {} (for [[k v] new-names] [v (get m k)]))
If you want a really simple piece of code, you could use fmap
function from algo.generic
library:
(fmap m (map-invert new-names))
Upvotes: 10