I have an vector and a map. And want to replace the vector element if it is an map key (replace the key with value)
user=> (def v [:a :b :c :d])
#'user/v
user=> (def m {:a :k, :c :q} )
#'user/m
user=> (reduce (fn[x y] (conj x (if (y m) (y m) y))) [] v)
[:k :b :q :d]
Is there any better way to do it?
Since your input and output are collections of the same length and the collection items are calculated independently, it would be simpler and more idiomatic to use map
, or mapv
for vector output.
(mapv (fn [x] (m x x))
v)
or simply
(mapv #(m % %) v)
Note that (m x x)
is similar to (if (contains? m x) (m x) x)
.
replace does exactly what you want :
user> (replace {:a :x :b :y} [:a :b :c :d :e :f])
[:x :y :c :d :e :f]
Note it works with vectors as an associative collection where keys are indices :
user> (replace [:a :b :c :d] [0 2 4 3 2 1])
[:a :c 4 :d :c :b]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With