Clojure supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.
To run this Clojure program:
In this Clojure version:
We define int-seq which returns an anonymous function. This function closes over an atom i, forming a closure.
The anonymous function uses swap! to increment the atom and return its new value.
In the -main function, we demonstrate the use of the closure by calling it multiple times and showing how it maintains its own state.
We also create a second closure to show that each instance maintains its own independent state.
The last feature of functions we’ll look at for now is recursion.