1

Looking at the way some special forms expand:

(macroexpand '(String. "foo"))
(macroexpand '('a))
;; etc

... and realizing they are implemented as macros makes me curious as to what are the syntactic form limits for user-defined macros. So far, all my macros resemble functions in their syntactic form. But would it be possible, for instance, to define a macro that like the following?:

(macroexpand '(myprintln-foo))
;;=> (println "foo")
(macroexpand '(myprintln-zoo))
;;=> (println "zoo")
Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331

2 Answers2

3

The limitation is that the macro must have a single valid name and return a single expression. It can't for instance tack something onto the end of the expression before it in the calling namespace, nor can it return two expressions to be inserted into the calling namespace sequentially (without making it one expression by wrapping it in a do. You could write a macro to define lots of macros:

(defmacro make-printers [& names]
  `(do ~@(for [name  names]
           `(defmacro ~(symbol (str "myprintln-" name)) []
              (println ~(str name))))))

user> (make-printers foo bar)
#'user/myprintln-bar
user> (myprintln-foo)

foo
nil 
user> (myprintln-bar) 
bar
nil 

Macros are just functions that return an s-expression. That expression can be anything so long as it is a valid s-expression (function arg arg ...). The name of the macro must match exactly for the macro to be called, so the name of the macro cannot be part of the macro. You can get close to what you are asking about with the new extensible reader feature though it's not quite what you need.

ps: It is worth pointing out that this example violates the first rule of macro club and is "unhygenic"

Arthur Ulfeldt
  • 90,827
  • 27
  • 201
  • 284
  • please see update. What I meant was whether it is possible to somehow affect the tokenization of the characters and the recognition of what constitutes a token. Otherwise, in the case of the macroexpansion of "String." it is not clear to me what is the macro name that gets expanded (I don't suppose a macro "String." is hardcoded-ly defined) – Marcus Junius Brutus Mar 04 '13 at 18:53
1

if I understand correctly, you are trying to write a reader macro and the short answer is 'no, it is not possible' (or at least not supported).

take a look at this article and its comments

Francisco Meza
  • 875
  • 6
  • 8