Named Functions

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Anonymous Funct ions | TOC | Higher-Order 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​ square (​fn​ ([x] (* x x))))

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

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

The first argument to defn is the name of the function being defined. It’s 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, but we could pass as many items as we like.

​ (​defn​ bmi [height weight]
​ (println ​"height:"​ height)
​ (println ​"weight:"​ weight)
​ (/ weight (* height height)))

Here we define a function to calculate BMI using the height and weight parameters. The body consists of two print statements and a call to divide the weight by the square of the height. All the expressions are evaluated from the inside out. In the last statement, (* height height) is evaluated, then the weight is divided by the result and returned. In…

--

--

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.