Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: Rename and select keys from map with one iteration

Tags:

clojure

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?

like image 216
Asher Avatar asked Nov 01 '25 02:11

Asher


1 Answers

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))
like image 101
Leonid Beschastny Avatar answered Nov 03 '25 21:11

Leonid Beschastny