Welcome! Please see the About page for a little more info on how this works.

0 votes
in Multimethods by

Hello,

I’ve reading about the Self language, and got experimenting with multi-methods to mimick Self-style messages. I was curious what folks think about this pattern:

(ns self)

(def path "./hello.txt")

(defn inst [msg]
(if (map? msg) (keys msg) msg)
)

(defmulti hello inst)

(defmethod hello [:save] [msg]
(spit path (msg :save))
)

(defmethod hello :load [msg]
(slurp path)
)

(defn do-run [h]
(h {:save "world"})
(println (h :load))
)

(defn run [opts]
(do-run hello)
)

Do you find this pattern interesting, useful? The example doesn’t show it, but there could be messages with multiple keywords.

Thanks,
- Quenio

1 Answer

+1 vote
by

You could also look at building something on top of clojure.core.match. Do not feel boxed-in by multimethods! Or you might be able to get closer to the ideal by writing your own macros to do the dispatching. One thing to watch out for, using Clojure's built-in multimethods dispatching by keys, is that message maps must not have any "extra" keys. For the most part, Clojure patterns embrace the idea that you can stuff extra keys into a map without breaking contracts.

...