Skip to content

Instantly share code, notes, and snippets.

@jneen
Created November 22, 2014 20:55
Show Gist options
  • Save jneen/f9f6ca49bdf8efc39ec2 to your computer and use it in GitHub Desktop.
Save jneen/f9f6ca49bdf8efc39ec2 to your computer and use it in GitHub Desktop.
Multimethods with variants
; it's a bit cumbersome to set up and there's the unfortunate need to ignore the tag
; in the individual methods, but this allows you to leave the interpretation of open
; variants, well, *open* for extension by multimethod.
; dispatch off the first argument, which will be the tag
(defmethod command-multi (fn [tag & data] tag))
; the first argument to the *method* is still the tag
(defmulti command-multi :print [_ val] (println val))
(defmulti command-multi :read [_ fname] (slurp fname))
; partially applying `apply` so that the variant vectors
; get flattened - it's a bit odd but gets the job done
(def command (partial apply command-multi))
(command [:print "hello world"]) ; prints "hello world"
(command [:read "./project.clj"]) ; returns the contents of project.clj
@clojj
Copy link

clojj commented Feb 17, 2015

any inspirations about leveraging clojure hierarchies for these variants ...?
see here:

So that :foo-hound isa ::foo-species
...and 'species-commands' get evaluated as well ...?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment