Clojure封闭 [英] Clojure closure
问题描述
前几天,我试图提出Clojure中关闭的示例.我想出了一个以前见过的例子,并认为这是适当的.
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.
A,有人告诉我这不是一个好东西,我应该让let提供一些东西.
Alas, I was told it was not a good one and that I should provide something with let.
谁能给我一些启示?
(defn pow [x n] (apply * (repeat x n)))
(defn sq [y] (pow y 2))
(defn qb [y] (pow y 3))
推荐答案
闭包是一种函数,可以在其自己的作用域之外访问某些命名的值/变量,因此可以在创建该函数时从更高的范围进行访问(此操作排除函数参数和在函数内创建的本地命名值).您的示例不符合条件,因为每个函数仅使用其自身作用域中的命名值.
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.
示例:
(def foo
(let [counter (atom 0)]
(fn [] (do (swap! counter inc) @counter))))
(foo) ;;=> 1
(foo) ;;=> 2
(foo) ;;=> 3, etc
现在 foo
是一个函数,该函数返回超出其范围的原子的值.因为该函数仍然保留对该原子的引用,所以只要需要 foo
,就不会对该原子进行垃圾回收.
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.
这篇关于Clojure封闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!