1

I seem to be coming up with too many multi-dispatch functions and would like to reduced the number. The approach I am currently using is to have a multi-function call another multifunction but that seems wrong. Here is an example of what I would like:

(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>))
...

The basic idea being that in the first case the method does not care what the third element of the dispatch value is, it will take them anything, but the second element must be :y.

Is something like this possible in clojure?

I may be asking for predicate dispatch, which, I guess, is still a work in progress.

4

1 回答 1

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
      )
于 2014-07-05T07:40:57.980 回答