Anonymous Functions

As the name implies, anonymous functions are simply functions that aren’t bound to a name. Let’s take a look at the following function that accepts a single argument and prints it.

 (​fn​ [arg] (println arg))

The function is defined by using the fn form followed by the vector containing its argument and the body. We could call the preceding function by setting it as the first item in a list and its argument as the second.

 ((​fn​ [arg] (println arg)) ​"hello"​)
 
 =>​"hello"

Clojure provides syntactic sugar for defining anonymous functions using the # notation. With it we can rewrite our function more concisely:

 #(println %)

Here, the % symbol indicates an unnamed argument. If the function accepted multiple arguments, ...

Get Web Development with Clojure, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.