Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Created April 8, 2010 14:52
Show Gist options
  • Save pervognsen/360145 to your computer and use it in GitHub Desktop.
Save pervognsen/360145 to your computer and use it in GitHub Desktop.
(defn uninterleave [xs]
[(take-nth 2 xs) (take-nth 2 (rest xs))])
(defmacro defnkw [name & handlers]
(let [handlers (map #(do [(uninterleave (first %)), (rest %)]) handlers)
selector- (gensym "selector")
args- (gensym "args")]
`(defn ~name [& selector-args#]
(let [[~selector- ~args-] (uninterleave selector-args#)]
(cond ~@(mapcat (fn [[[test-selector params] body]]
`((= ~selector- '~test-selector)
(let [~(vec params) ~args-]
~@body)))
handlers)
:else (throw (Exception. "No matching selector found.")))))))
;; Examples
(defnkw please
([:multiply x :by y] (* x y))
([:add x :to y] (+ x y)))
(please :multiply 2 :by 3) ;; 6
(please :add 2 :to 3) ;; 5
(please :divide 2 :by 3) ;; "No matching selector found."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment