我有一些使用多方法的代码,并且想要重载函数(在这种情况下,是多函数),以便我可以传递一个高阶函数来帮助测试,例如。
以下是示例:
(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提供了重载功能,不过我想知道defmethod是否支持类似的功能。(我猜你不会希望为每个defmethod声明都这么做。)
这是最合适的方法吗(我敢说是“惯用”的方法),还是有更好的方法?