Named Functions

Named functions are simply anonymous functions bound to a symbol used as an identifier. Clojure provides a special form called def that’s used for creating global variables. It accepts a name and the body to be assigned to it. We can create a named function by using def as follows:

 
(​def​ ​double​ (​fn​ ([x] (​*​ 2 x))))

Since this is such a common operation, Clojure provides a special form called defn that does it for us:

 
(​defn​ square [x]
 
(​*​ x x))

The first argument to defn is the name of the function being defined. It is followed by a vector containing the arguments and the body of the function. In the preceding code, we passed in a single item for the body; however, we could pass as many items as we like:

 
(​ ...

Get Web Development with Clojure 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.