Clojure defmethod Pattern Match Dispatch-Value

时间:2014-07-05 00:56:25

标签: clojure dispatch multimethod

我似乎想出了太多的多调度功能,并希望减少数量。我目前使用的方法是让多功能调用另一个多功能,但这似乎是错误的。这是我想要的一个例子:

(defmulti foo
(fn [bar baz] [(:type bar) (:x baz) (:y bar)]))

(defmethod foo [:z :y _] [bar baz] (<I will take anything for the 3rd element>))
(defmethod foo [:z  _ :x] [bar baz] (<I will take anything for the 2nd element>))
(defmethod foo [:z :y :x] [bar baz] (<I must have this dispatch value>))
...

基本思想是,在第一种情况下,方法不关心调度值的第三个元素是什么,它将采取任何东西,但第二个元素必须是:y。

这样的事情在clojure中是否可能?

我可能会要求谓词调度,我猜,这仍然是一项正在进行的工作。

1 个答案:

答案 0 :(得分:2)

似乎你需要正确的模式匹配,在这种情况下core.match就是你想要的。

使用core.match,您可以编写如下内容:

(match [(:type bar) (:x baz) (:y bar)]
      [:z :y _] ;;  accepts anything as the 3rd element
      [:z _ :x] ;;  accepts anything as the 2nd element
      [:z :y :x] ;; accepts precisely these values
      )