Pointers 如何传递函数引用,而不是函数本身?
假设我们定义了函数Pointers 如何传递函数引用,而不是函数本身?,pointers,clojure,reference,Pointers,Clojure,Reference,假设我们定义了函数my function,它将打印“message1”。 接下来在repl中,我们定义了这个使用该函数的原子 (def key-func (atom {:func my-function})) 之后,我更新函数my function,以打印“message2”。 现在,当我运行(:func@key func))时,它会打印“message1”。我最后不得不重新装填原子弹。这会让我相信,{:func my function}并不是将对实际函数的引用与:func配对,而是传递当时函
my function
,它将打印“message1”
。
接下来在repl中,我们定义了这个使用该函数的原子
(def key-func (atom {:func my-function}))
之后,我更新函数my function
,以打印“message2”
。
现在,当我运行(:func@key func))
时,它会打印“message1”
。我最后不得不重新装填原子弹。这会让我相信,{:func my function}
并不是将对实际函数的引用与:func
配对,而是传递当时函数的副本。那么,是否可以传递函数指针而不是副本
TLDR
简短回答
见这个问题:
更长的答案
您正在以非标准方式使用atom。我认为以下内容更接近您的要求:
(defn f1 [] "#1")
(defn f2 [] "#2")
(def my-fn (atom f1))
(println :1 (@my-fn))
(reset! my-fn f2)
(println :2 (@my-fn))
生成:
:1 #1
:2 #2
最长版本
此示例显示了复制函数与复制指向函数的变量之间的区别:
; This will not work, since his-fn saves a ref to the
; immutible "All yours baby!" function
(newline)
(println "-----------------------------------------------------------------------------")
(defn your-fn [] (println "All yours baby!"))
(your-fn) ;=> "All yours baby!"
(def his-fn your-fn)
(his-fn) ;=> "All yours baby!"
(defn your-fn [] (println "And it still is!"))
(his-fn) ;=> "All yours baby!"
; This will work, since both his-fn and her-fn save a reference
; to the var `your-fn`, which in turn points to first to
; one function and then to a second function.
(newline)
(println "-----------------------------------------------------------------------------")
(defn your-fn [] (println "All yours baby!"))
(your-fn)
(def his-fn (var your-fn))
(def her-fn #'your-fn)
(his-fn)
(her-fn)
; change what var "your-fn" points to
(defn your-fn [] (println "And now you belong to me..."))
(his-fn)
(her-fn)
结果如下:
;-----------------------------------------------------------------------------
;=> All yours baby!
;=> All yours baby!
;=> All yours baby!
-----------------------------------------------------------------------------
;=> All yours baby!
;=> All yours baby!
;=> All yours baby!
;=> And now you belong to me...
;=> And now you belong to me...
警告
在演示了变量的行为之后,请记住重新定义顶级表单(如
(def…
和(defn…
)是不好的。通常最好使用atom或局部变量来保存不断变化的值。我认为我使用的术语指针和引用是正确的,但如果我没有正确使用,请纠正我,我会解决这个问题。作为对警告的回应:我理解重新定义顶级表单是一种不好的做法。我的案例是开发,这些通常不会更改的顶级表单经常被重新加载以进行测试。我希望更新后的函数反映在状态原子中,而不是重新加载。
;-----------------------------------------------------------------------------
;=> All yours baby!
;=> All yours baby!
;=> All yours baby!
-----------------------------------------------------------------------------
;=> All yours baby!
;=> All yours baby!
;=> All yours baby!
;=> And now you belong to me...
;=> And now you belong to me...