4

快速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 等...

4

2 回答 2

7
(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很好。

于 2013-05-01T22:49:53.843 回答
2

如果你使用type代替class,代码也可以在 ClojureScript 中工作。

于 2020-02-08T18:17:17.250 回答