Dav*_*ams 4 clojure signature method-signature multimethod
快速的clojure问题,我认为这主要与语法有关.如何根据参数的特定类型签名调度多方法,例如:
(defn foo
([String a String b] (println a b))
([Long a Long b] (println (+ a b))
([String a Long b] (println a (str b))))
Run Code Online (Sandbox Code Playgroud)
我想把它扩展到任意的东西,例如两个字符串后跟一个地图,映射后跟一个double,两个双精度后跟一个IFn等......
(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)))
Run Code Online (Sandbox Code Playgroud)
来自REPL:
user=> (foo "bar" "baz")
bar baz
nil
user=> (foo 1 2)
3
nil
Run Code Online (Sandbox Code Playgroud)
您也可以考虑使用type而不是class; type返回:type元数据,class如果没有则委托给.
此外,class2不必在顶层定义; 路过(fn [x y] ...)的调度功能defmulti是好的了.