2013-05-01 55 views
3

快速clojure问题,我认为这主要是语法相关的。我如何调度基础上的论点特定类型签名一个多重方法,例如:Clojure:defmulti对不同类的类型

(defn foo 
    ([String a String b] (println a b)) 
    ([Long a Long b] (println (+ a b)) 
    ([String a Long b] (println a (str b)))) 

我想将其扩展到任意的东西,如两个字符串后面的地图,以地图后跟双,双双打接着是干扰素等..

回答

6
(defn class2 [x y] 
    [(class x) (class y)]) 

(defmulti foo class2) 

(defmethod foo [String String] [a b] 
    (println a b)) 

(defmethod foo [Long Long] [a b] 
    (println (+ a b))) 

从REPL:

user=> (foo "bar" "baz") 
bar baz 
nil 
user=> (foo 1 2) 
3 
nil 

你也可以考虑使用type代替class; type返回:type元数据,如果没有,则委托给class

另外,class2不必在顶层定义;作为派遣功能(fn [x y] ...)defmulti也很好。