clojure Functions Defining anonymous functions


Example

There are two ways to define an anonymous function: the full syntax and a shorthand.

Full Anonymous Function Syntax

(fn [x y] (+ x y))

This expression evaluates to a function. Any syntax you can use with a function defined with defn (&, argument destructuring, etc.), you can also do with with the fn form. defn is actually a macro that just does (def (fn ...)).

Shorthand Anonymous Function Syntax

#(+ %1 %2)

This is the shorthand notation. Using the shorthand notation, you don't have to name arguments explicitly; they'll be assigned the names %1, %2, %3 and so on according to the order they're passed in. If the function only has one argument, its argument is called just %.

When To Use Each

The shorthand notation has some limitations. You can't destructure an argument, and you can't nest shorthand anonymous functions. The following code throws an error:

(def f #(map #(+ %1 2) %1))

Supported Syntax

You can use varargs with shorthand anonymous functions. This is completely legal:

#(every? even? %&)

It takes a variable number of arguments and returns true if every one of them is even:

(#(every? even? %&) 2 4 6 8)
;; true
(#(every? even? %&) 1 2 4 6)
;; false

Despite the apparent contradiction, it is possible to write a named anonymous function by including a name, as in the following example. This is especially useful if the function needs to call itself but also in stack traces.

(fn addition [& addends] (apply + addends))