Follow @dstiberova

Closures in Clojure

October 12, 2015

While solving 4clojure problems, I encountered simple closures. I had to find out more about closures, and I found them really interesting. So I decided to write a short post about my new knowledge.

The term Closure comes from fact that the code snippet (code block), has a free variables that can not be used or called from outside. They can be used only inside the function in which the code block is defined . That means, they are closed by the environment in which the block of code is defined.

A closure allows the function to access those variables through the closure's reference to them, even when the function is invoked outside their environment (this environment is known as lexical scope). Outer variable referenced by the closure is called captured variable .

We will create a power function in Clojure utilizing Closure

Result

(fn [y] (apply * (repeat x y))) is anonymous function in the lexical scope of the power function. The inner function (fn [y] (apply * (repeat x y))) uses argument x which is given from outer function (defn power [x] ..) . This code block defines closure.