> Hey folks,
>
> I have a case where I want several dispatch values in a multimethod to
> map to the same method. For example, for a dispatch value of 1 I want
> it to call method-a, however, for dispatch values of 2, 3, or 4 I want
> it to call method-b. Is there a way to do this with the existing
> multimethod mechanism?
Yes, here's one way:
(defmulti foo
[nil
:method-1,
:method-2,
:method-2,
:method-2])
(defmethod foo :method-1
[x]
(println "method-1"))
(defmethod foo :method-2
[x]
(println "method-2"))
----------------------
user=> (dotimes i 4 (foo (inc i)))
method-1
method-2
method-2
method-2
nil
user=>
----------------------
The nil at index 0 in the vector is a little ugly... you could use a
map instead or a function that uses "if".
--Steve
I'm still learning so please let me know if there is a
simpler or more concise way to use the map for multi-method dispatch.
You are in control here, and everywhere you store a reference to a
function, as to whether you want to capture the var's function value
or maintain a connection to the var that contains its current
definition. To get the latter effect, just pass the var itself rather
than its value:
(defmulti tst #'tst-dispatch)
vars implement IFn by delegating to their values:
user=> (first [1 2])
1
user=> (#'first [1 2]) ;call through var
1
user=> ((var first) [1 2]) ;previous is a shorthand for this
1
so doing the above allows you to fix tst-dispatch and have the
multimethod pick up the fix.
Rich