Skip to content

Instantly share code, notes, and snippets.

@roneesh
Last active August 29, 2015 14:22
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 roneesh/64ecd0bae69ec0efc8a2 to your computer and use it in GitHub Desktop.
Save roneesh/64ecd0bae69ec0efc8a2 to your computer and use it in GitHub Desktop.
A clojure multi-if macro
; first try
; broke because the macro ended up evaluating the condition and just being an instruciton to do the pass or fail
;(defmacro multi-if [test pass fail] (list 'if test (do pass) (do fail)))
; second try including arity and notice the returning of a construction
;(defmacro multi-if [test & {then :then else :else}] (list 'if test (cons 'do then) (cons 'do else)))
; third try, seems to have proper way of supplying map to macro as argument
;(defmacro multi-if [test & {:keys [then else]}] (list 'if test (cons 'do then) (cons 'do else)))
; I see now that this third try produces a macro like the following...
;(macroexpand '(multi-if (> 3 1) :then (+ 3 1)))
; => (if (> 3 1) (do + 3 1) (do))
; when I really need it to produce...
; => (if (> 3 1) (do (+ 3 1)) (do))
; e-mail from mike said I had two questions, but I realize I got the macro wrong, was getting answers in the style of:
;user=> (multi-if (> 3 1) :then ("ok"))
;"ok"
;which I now know isn't right
; fourth try, I think I'm closer...
(defmacro multi-if [test & {:keys [then else]}] (list 'if test (cons 'do [then]) (cons 'do [else])))
; user=> (macroexpand '(multi-if (> 3 1) :then (+ (+ 3 1) (inc 5))))
; produces: (if (> 3 1) (do (+ (+ 3 1) (inc 5))) (do nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment