You're viewing version 1.2.0 of replace. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

replace

clojure.core

  • (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

3 Examples top

  • 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 '{0 ZERO, 1 ONE, 2 TWO} '(This is the code — 0 1 2 0))
    (This is the code — ZERO ONE TWO ZERO)
    
    user=> (replace {2 :two, 4 :four} [4 2 3 4 5 6 2])
    [:four :two 3 :four 5 6 :two]
    
  • ; 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)
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:3979 top

(defn replace
  "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"
  {:added "1.0"}
  [smap coll]
    (if (vector? coll)
      (reduce (fn [v i]
                (if-let [e (find smap (nth v i))]
                        (assoc v i (val e))
                        v))
              coll (range (count coll)))
      (map #(if-let [e (find smap %)] (val e) %) coll)))
Vars in clojure.core/replace: assoc count defn fn if-let map range reduce val vector?

Comments top

1 comment(s) for replace.

The behaviour for vectors was a little strange for me. I'd say replace "selects" from "smap" the indexes which are in "coll"

Log in to add a comment.