the other day I was trying to come up with an example of closure in Clojure. I came up with and example I had seen before and thought it was appropriate.
Alas, I was told it was not a good one and that I should provide something with let.
Can anyone shed some light?
(defn pow [x n] (apply * (repeat x n))) (defn sq [y] (pow y 2)) (defn qb [y] (pow y 3))
Clojure has closures, and closures are an excellent way to group functions (Crockford 2008) with their supporting data.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment.
Closures are important because they control what is and isn't in scope in a particular function, along with which variables are shared between sibling functions in the same containing scope.
A closure is a function that has access to some named value/variable outside its own scope, so from a higher scope surrounding the function when it was created (this excludes function arguments and local named values created within the function). Your examples do not qualify, because every function just uses named values from their own scopes.
Example:
(def foo (let [counter (atom 0)] (fn [] (do (swap! counter inc) @counter)))) (foo) ;;=> 1 (foo) ;;=> 2 (foo) ;;=> 3, etc
Now foo
is a function that returns the value of an atom that is outside its scope. Because the function still holds a reference to that atom, the atom will not be garbage-collected as long as foo
is needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With