Tiny Clojure Tips - Part 1

Suppose you love Clojure (of course you do), anonymous functions (doubly so!), and syntactic sugar but you need to have more than one argument. What's a person to do?! You could write the anonymous function out like so, but look at that - an extra pair of extra parentheses. Even an extra pair of brackets! Eww!

(map (fn [x y] (str x y)) ["cat" "hea" "mat"] ["food" "t" "ter"])
;=> ("catfood" "heat" "matter")

Instead, why not use this shorthand:

(map #(str %1 %2) ["cat" "hea" "mat"] ["food" "t" "ter"])
;=> ("catfood" "heat" "matter")

The secret is in the digit following the %. This indicates the position of the argument to use, see:

(map #(str %2 %1) ["cat" "hea" "mat"] ["food" "t" "ter"])
;=> ("foodcat" "thea" "termat")

REPL REPL Everywhere

Ever read the information displayed right after the REPL is loaded? All sorts of goodies in there, but especially this line:

Results: Stored in vars *1, *2, *3, an exception in *e

Turns out, you can use it exactly as described:

user=> (str "hi")
user=> (str "cat" *1)
user=> (str *1 *2)