Anonymous functions
There's a quicker way to create anonymous functions with a bit of syntactic sugar. That previous example:
(fn [r]
(* r 3.14 3.14))
can be expressed like so:
#(* % 3.14 3.14)
As you see, there's no explicit parameters list. Instead, we just write the body and refer to the argument as %
. If there are several arguments, we can refer to them via %1
, %2
, etc. Here's a anonymous function that takes 3 numbers and returns the average:
#(/ (+ %1 %2 %3) 3)
Let's call this function. At this point it might look alien, but nothing had changed — to call a function simply put it in front of arguments and wrap the whole thing in parens:
user=> (#(/ (+ %1 %2 %3) 3) 10 13 19)
14
user=> (#(/ (+ %1 %2 %3) 3) 1 2 3)
2
user=> (#(/ (+ %1 %2 %3) 3) -12 8 188)
184/3
(Note how Clojure had returned a ratio as the answer, not a regular floating point number.)
Why though? This looks increasingly cryptic. Such syntax is useful when you need to create a small function, usually as a part of some higher-order function call. Remember the dinc
example? We could've done this:
user=> (map #(+ % 2) (range 5 8))
(7 8 9)
#(+ % 2)
is an anonymous function which adds 2
to its only argument and returns the answer.