Created
April 8, 2010 14:52
-
-
Save pervognsen/360145 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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