2
votes

I am learning Macros in Clojure and wanted to write the "cond" macro.

I am having problem de-structuring the arguments into (condition) (arguments) and writing a recursive macro.

Please help me.

1

1 Answers

4
votes

I'm writing this to illustrate the process. this code has lots of bugs but the process will get you to the fun part as quickly as possible :) write out the call to your macro and what you want that call to translate into (this step is not optional ;)

(my-cond (even? 4) 42 (odd? 4 24))

(if (even? 4) 42 (if (odd? 4) 24)))

write a template for the simplest case and then feed it to (macroexpand-1 ... ) and twiddle until it matches

(defmacro my-cond [test result] `(if ~test ~result nil))

(macroexpand-1 '(my-cond (even? 4) 42) ==> (if (even? 4) 42)

now make it more general

(defmacro my-cond [& cases]
  `(if (if ~(first cases) ~(second cases) ~(my-cond (drop 2 cases))

and then play with it in macroexpand-1 then in macroexpand (with out the "-1") to make sure that it fully expands into the correct cases
then go through and clean up the corner cases where there are an odd number of terms etc...

then look in core.clj and see how close you got.