Lookup
1 2 3 4 |
(defn lookup "Look up a value, i, in map m and returns the result if it exists. Otherwise returns i." [i m] (get m i i)) |
Note that (get m i i) can be abbreviated (m i i) since Clojure allows maps to be in function position in order to perform lookups.
Usage example:
1 2 3 4 |
user=> (lookup 'b '{a 1 b 2}) 2 user=> (lookup 'c '{a 1 b 2}) c |
Substitute
1 2 3 4 5 |
(defn substitute "Given a map of replacement key/value pairs, m, and a list, l, returns a list with values from l, but with any elements equal to a key in m replaced with the corresponding val in m." [l m] (map (fn [i] (lookup i m)) l)) |
Usage example:
1 2 |
user=> (substitute '(a c b d) '{a 1, b 2} ) (1 c 2 d) |
Note: There is a shortcut syntax for building lambda (anonymous) functions. Instead of (fn [i] ...) write #( ... ). If the anonymous function is of only one variable it is called %. If you have more than one they are %1, %2, … So this could be rewritten:
1 2 3 4 5 |
(defn substitute "Given a map of replacement key/value pairs, m, and a list, l, returns a list with values from l, but with any elements equal to a key in m replaced with the corresponding val in m." [l m] (map #(lookup % m) l)) |
Deep Substitute
1 2 3 4 5 6 7 8 9 10 |
(defn deep-substitute "Given a map of replacement key/value pairs, m, and a list, l, returns a list with values from l, but with any elements equal to a key in m replaced with the corresponding val in m. If l contains nested lists, recursively performs replacement in those lists as well." [l m] (map (fn [i] (if (seq? i) (deep-substitute i m) (lookup i m))) l)) |
Usage example:
1 2 |
user=> (deep-substitute '(a (b a) (c) d) '{a 1, b 2}) (1 (2 1) (c) d) |