replace

added
1.0

ns
clojure.core

type
function

(replace smap) (replace smap coll)

Given a map of replacement pairs and a vector/collection, returns a
vector/seq with any elements = a key in smap replaced with the
corresponding val in smap.  Returns a transducer when no collection
is provided.

                user=> (replace [:zeroth :first :second :third :fourth] [0 2 4 0])
[:zeroth :second :fourth :zeroth]

user=> (replace [10 9 8 7 6] [0 2 4])
[10 8 6]
            
                user=> (replace {2 :two, 4 :four} [4 2 3 4 5 6 2])
[:four :two 3 :four 5 6 :two]

user=> (replace '{0 ZERO, 1 ONE, 2 TWO} '(This is the code 0 1 2 0))
(This is the code ZERO ONE TWO ZERO)
            
                ; Behaves somewhat similar to map, but notice the differences
user=> (map [:zeroth :first :second :third :fourth] [0 2 4 0])
(:zeroth :second :fourth :zeroth)

; 1. replace returns a vector, while map returns a seq
; 2. replace keeps unmatched values, while map replace with nil
user=> (map {} [0])
(nil)
user=> (map [] [0])
IndexOutOfBoundsException   clojure.lang.PersistentVector.arrayFor (PersistentVector.java:107)

            
                user=> (replace {2 :a, 4 :b} [1 2 3 4])
;;=> [1 :a 3 :b]