Anonymous Functions

Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (68 / 107)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Using Functions | TOC | Named 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, then each one would be followed by a number indicating its position. This can be seen in the next example:

​ #(println %1 %2 %3)

The preceding anonymous function accepts three arguments and prints them out in order. This type of function is useful when you need to perform a one-off operation that doesn’t warrant defining a named function. These functions are often used in conjunction with the higher-order functions that we’ll look at in a…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.