dagda1
dagda1

Reputation: 28950

Unsure of clojure type

Can anybody explain what the type below is in the code below which I seen in the clojure docs for string/replace?

(clojure.string/replace "The color is red" #"red" "blue")

I am talking specifically about the #"red" "blue"

Also, if I have an array-map like this:

{"red" "blue"}

How could I transform this array-map into this unknown type?

{"red" "blue"} ;=> #"red" "blue"??? 

Upvotes: 0

Views: 68

Answers (2)

Alex Miller
Alex Miller

Reputation: 70239

If you have a map {"red" "blue"} and you'd like to use that to drive the replacement, you could do:

;; Generic form of your question - uses re-pattern to create a regex
(defn replace-with [s find replacement]
  (clojure.string/replace s (re-pattern find) replacement))

;; Walk through every [find replace] pair in replacements map 
;; and repeatedly apply it to string
(defn replace-with-all [s replacements]
  (reduce (fn [s [f r]] (replace-with s f r)) 
          s
          replacements))

(replace-with-all "foo bar baz" {"foo" "blue" "baz" "red"})
;; "blue bar red"

Upvotes: 4

Chiron
Chiron

Reputation: 20245

In Clojure, #"....." is a Regular Expression definition. So you are replacing red with blue.

(replace s match replacement)
Replaces all instance of match with replacement in s.

match/replacement can be:

string / string char / char pattern / (string or function of match).

But I didn't understand what do you mean by 'transform this array-map into this unknown type'.

Upvotes: 3

Related Questions