Lookup
(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:
user=> (lookup 'b '{a 1 b 2})
2
user=> (lookup 'c '{a 1 b 2})
c
Substitute
(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:
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:
(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
(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:
user=> (deep-substitute '(a (b a) (c) d) '{a 1, b 2})
(1 (2 1) (c) d)