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.

phreed
  • 1,759
  • 1
  • 15
  • 30

1 Answers1

3

Seems you need proper pattern matching, in which case core.match is what you want.

Using core.match, you can write something like:

(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
      )
leonardoborges
  • 5,579
  • 1
  • 24
  • 26