Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure closure

Tags:

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)) 
like image 874
Eddy Avatar asked Feb 14 '13 12:02

Eddy


People also ask

Does Clojure have closures?

Clojure has closures, and closures are an excellent way to group functions (Crockford 2008) with their supporting data.

What is closure give an example?

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.

What is closure language?

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.

Why are closures useful?

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.


1 Answers

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.

like image 58
Michiel Borkent Avatar answered Oct 25 '22 10:10

Michiel Borkent