例如,我有一些使用多方法的代码,理想情况下希望重载函数(在本例中为多功能),以便我可以传递更高阶的函数来帮助进行测试。
这是示例:
(ns multi)
(defn my-print [m] (println "The colour is" (:colour m)))
(defmulti which-colour-mm (fn [m f] (:colour m)))
(defmethod which-colour-mm :blue [m f] (f m))
(defmethod which-colour-mm :red [m f] (f m))
(defmethod which-colour-mm :default [m f] (println "Default: Neither Blue nor Red"))
(defn which-colour
([m] (which-colour-mm m my-print))
([m f] (which-colour-mm m f)))
(which-colour {:colour :blue :object :ball})
(which-colour {:colour :yellow :object :ball})
(which-colour {:colour :blue :animal :parrot} (fn [m] (println "The " (:animal m) "is" (:colour m))))
所以我的 defn 提供了 arity 重载,但我想知道 defmethod 是否支持这样的东西。(我猜你不想为每个 defmethod 声明都这样做。)
这是最合适的(我敢说,惯用的)方法,还是有更好的方法?