我认为多方法不会按照您期望的方式工作。
也就是说:对于单个多方法调用,多方法中的调度仅调用一次,因此除非您定义一个实现,否则无法获得您期望的结果(“正确!”打印为“一”和“二”作为参数)它实际上处理在输入字符串中同时包含\r
和的情况,\!
并打印您想要的输出。
这将不容易扩展。
实现您想要的更好的方法是通过迭代输入字符串显式地进行多次调用:
; You want the dispatch function to just return the character passed to it.
(defmulti foo identity)
; The argument list here is mandatory, but we don't use them at all, hence '_'
(defmethod foo \r [_]
(println "one"))
(defmethod foo \! [_]
(println "two"))
; You need the default case for all the other characters
(defmethod foo :default [_]
())
; Iterates the string and executes foo for each character
(defn bar [s]
(doseq [x s]
(foo x)))
所以打电话
(bar "right!")
将打印:
one
two
编辑
如果您需要访问多方法体内的整个字符串,则将其与字符一起显式传递:
; You want the dispatch function to just return the character passed to it as the first arg.
(defmulti foo (fn [c _] c))
(defmethod foo \r [c s]
(println "one"))
(defmethod foo \! [c s]
(println "two"))
; The default now takes two arguments which we ignore
(defmethod foo :default [_ _] ())
; Iterates the string and executes foo for each character
(defn bar [s]
(doseq [x s]
(foo x s)))