Closures

Next we’ll look at functions that return other functions as a result. One use for such functions is to provide behavior that is facilitated by constructors in object-oriented languages. For example, if you want to initialize some variables before using a function, you can do so as follows:

 
(​defn​ make-client [url]
 
(​fn​ [request] (​str​ ​"sending "​ request ​" to "​ url)))
 
(​let​ [client (make-client ​"http://foo.org"​)]
 
(​println​ (client ​"request 1"​))
 
(​println​ (client ​"request 2"​)))

Here we create a function that accepts a url parameter and returns a function that accepts a request as its parameter. The inner function has access to the url variable since it’s defined in the same scope.

This type of function is called ...

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.