Clojure closure

前端 未结 4 452
迷失自我
迷失自我 2021-01-31 19:43

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 tol

4条回答
  •  遇见更好的自我
    2021-01-31 20:17

    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.

提交回复
热议问题