gpt4 book ai didi

clojure - 如何在 Clojure REPL 中重新加载多方法

转载 作者:行者123 更新时间:2023-12-02 23:38:21 25 4
gpt4 key购买 nike

我正在REPL中编写一个多方法,可以重新定义函数,但是如果我重新定义多方法的调度函数,它似乎不能使用新改进的函数:

;; simple fn to resolve defmethod to call, hardcoded to :do-it
(defn resolve-it [] :do-it)
(resolve-it) ;; :do-it, as expected

(defmulti do-something resolve-it)

(defmethod do-something :do-it [] (println "do-it"))
(defmethod do-something :oh-no [] (println "oh-no"))

(do-something) ;; "do-it", as expected

;; now change resolve-it
(defn resolve-it [] :oh-no)
(resolve-it) ;; :oh-no, as expected

(do-something) ;; "do-it", not as expected

(do-something) ;; "do-it", not expected

如何使用 mult 方法来反射(reflect)对调度函数 resolve-it 的更改?

最佳答案

有一种简单的技术可以重新定义多方法的调度函数。这个想法是将保存调度函数的 var 传递给 defmulti,而不是函数本身。请注意 defmulti 中的 #'resolve-it 而不仅仅是 resolve-it。因此,var 在运行时被取消引用,而不仅仅是在编译时。

(defn resolve-it [] :do-it)
(resolve-it) ;; :do-it, as expected

(defmulti do-something #'resolve-it)

(defmethod do-something :do-it [] (println "do-it"))
(defmethod do-something :oh-no [] (println "oh-no"))

(do-something) ;; "do-it", as expected

;; now change resolve-it
(defn resolve-it [] :oh-no)
(resolve-it) ;; :oh-no, as expected

(do-something) ;; "oh-no", expected!!

关于clojure - 如何在 Clojure REPL 中重新加载多方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44807442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com