Created
December 19, 2011 00:54
-
-
Save samaaron/1494980 to your computer and use it in GitHub Desktop.
Clojure: mk-callable-map macro
This file contains hidden or 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
(defmacro mk-callable-map [] | |
(letfn [(arg-names [n] | |
(map #(symbol (str "v" (inc %))) (range n))) | |
(invoke-n [n] | |
(list 'invoke (vec (cons 'this (arg-names n))) | |
(list* 'callable-map-fn-impl (arg-names n)))) | |
(invoke-n-with-apply [n] | |
(list 'invoke (vec (cons 'this (arg-names n))) | |
(list* 'apply 'callable-map-fn-impl (arg-names n))))] | |
`(~'defrecord ~'CallableMap [~'callable-map-fn-impl] | |
clojure.lang.IFn | |
~@(map #(invoke-n %) (range 21)) | |
~(invoke-n-with-apply 21) | |
~'(applyTo [this arg-list] (clojure.lang.AFn/applyToHelper callable-map-fn-impl arg-list))))) | |
(mk-callable-map) | |
(def cm1 (CallableMap. (fn [a b] (println "with two args:" a b)))) | |
(cm1 1 2) | |
(def cm2 (CallableMap. (fn [& args] (println "with var args:" args)))) | |
(cm2 1 2) | |
(cm2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22) | |
(apply cm2 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wonder if there's a way to hide the key callable-map-fn-impl