【问题标题】:Clojure: defmulti on different class typesClojure:不同类类型上的 defmulti
【发布时间】:2013-05-01 21:36:54
【问题描述】:
快速 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))))
我想将此扩展到任意内容,例如两个字符串后跟一个映射,映射后跟一个双精度数,两个双精度数后跟一个 IFn 等...
【问题讨论】:
标签:
clojure
signature
method-signature
multimethod
【解决方案1】:
(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 也可以。
【解决方案2】:
如果您使用 type 而不是 class,则代码也可以在 ClojureScript 中运行。