Julia Writing Macros
A macro is code that rewrites other code before that code runs. It is called with @ before its name.
Twice doubles a variable
The macro returns quoted code that doubles its argument. The escaped argument refers to the caller's variable.
macro twice(ex)
return :(2 * $(esc(ex)))
end
x = 4
println(@twice x)Twice also doubles a sum
The argument arrives as code. A sum inside it stays grouped, so the result is 8.
macro twice(ex)
return :(2 * $(esc(ex)))
end
println(@twice (3 + 1))Macro expansion is a call expression
Macroexpand shows the code a macro call becomes. That code is a call expression with three parts.
macro twice(ex)
return :(2 * $(esc(ex)))
end
e = @macroexpand @twice x
println(typeof(e))
println(e.head)
println(length(e.args))Example
macro twice(ex)
return :(2 * $(esc(ex)))
end
a = 3
println(@twice a)
println(@twice (a + 2))
e = @macroexpand @twice a
println(typeof(e))
println(e.head)Key points
- Macro: define one with the macro keyword and call it with @ before its name.
- Rewrite: a macro returns a quoted expression, and Julia runs that expression in place of the call.
- Argument: a macro receives its argument as code, not as a computed value.
- Escape: use esc to mark an argument as the caller's variable.
- Expansion: macroexpand shows the code a macro call becomes.
In this example, twice is defined once. It doubles a, then it doubles a plus 2. The last two lines show the expansion is a call expression.
Note
a macro call needs @, while a plain function call does not.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What is the value of @twice 5 when twice doubles its argument?