Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace vector using map in clojure

Tags:

clojure

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?

like image 511
Daniel Wu Avatar asked Mar 18 '23 06:03

Daniel Wu


2 Answers

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).

like image 116
TheQuickBrownFox Avatar answered Mar 29 '23 19:03

TheQuickBrownFox


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]
like image 27
T.Gounelle Avatar answered Mar 29 '23 19:03

T.Gounelle