3
votes

If I want to decompose a macro in Clojure, are there any differences (functional or otherwise) in declaring functions or macros to be the sub-components?

i.e. are there any differences between

(defn sub-function [x] ...)

(defmacro main-macro [x]
  (sub-function x))

vs

(defmacro sub-macro [x] ...)

(defmacro main-macro [x]
  (sub-macro x))

My list so far is:

  1. I can't recur within my sub-macro but I can within my sub-function

  2. I can't refactor my main macro to use a sub-macro as a higher order function

  3. I can call my sub-function as a regular runtime function

Using sub-functions means I can't call them directly as macros but I could always wrap any sub-function within another macro if I want its functionality at compile time.

All these points are fairly trivial; Are there any conventions or stronger arguments for/against using sub-functions/sub-macros?

1

1 Answers

4
votes

Always do the first one unless you absolutely can't.

The first rule of "macro club"(PDF) is "don't write a macro". And if you must write a macro or want to provide a nice syntax to some action it can be very very irritating if the macro is the only interface to that function. If instead of making sub-macros you instead create macros that call normal functions, then others are free to extend your code using functions or macros. If you use further macros to decompose them then you create "macro contagion" which forces everyone who extends your library to only write macros.

The most common case I see where I cannot decompose a macro with functions is when the things it's decomposing into are already macros themselves from some other library and it's incredibly frustrating. Your colleagues and your future self will thank you if you can manage to take the function option.