Skip to content

Instantly share code, notes, and snippets.

@samaaron
Created December 19, 2011 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samaaron/1494980 to your computer and use it in GitHub Desktop.
Save samaaron/1494980 to your computer and use it in GitHub Desktop.
Clojure: mk-callable-map macro
(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])
@samaaron
Copy link
Author

I wonder if there's a way to hide the key callable-map-fn-impl

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