Closures

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Higher-Order Functions | TOC | Threading Expressions 👉

We’ve now seen how we can declare functions, name them, and pass them as parameters to other functions. One last thing we can do is write functions that return other functions as their result. One use for this is to provide the functionality facilitated by constructors in object-oriented languages.

Let’s say we wish to greet our guests warmly. We can write a function that accepts the greeting string as its parameter and returns a function that takes the name of the guest and prints a customized greeting for that guest:

​ (​defn​ greeting [greeting-string]
​ (​fn​ [guest]
​ (println greeting-string guest)))

​ (​let​ [greet (​greeting​ ​"Welcome to the wonderful world of Clojure"​)]
​ (​greet​ ​"Jane"​)
​ (​greet​ ​"John"​))

The inner function in the greeting has access to the greeting-string value since the value is defined in its outer scope. The greeting function is called a closure because it closes over its parameters — in our case the greeting-string — and makes them available to the function that it returns.

You’ll also notice that we’re using a form called let to bind the greet symbol and make it available to any expressions inside it. The let form serves the same purpose as declaring variables in imperative languages.

👈 Higher-Order Functions | TOC | Threading Expressions 👉

Web Development with Clojure, Third Edition by Dmitri Sotnikov, Scot Brown can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.

--

--

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.