O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Macros Are Hygienic

It is tempting to think of macros as some kind of textual substitution—a macro’s body is expanded as text and then compiled at the point of call. But that’s not the case. Consider this example:

macros/hygiene.ex
 
defmodule​ Scope ​do
 
defmacro​ update_local(val) ​do
 
local = ​"some value"
 
result = ​quote​ ​do
 
local = ​unquote​(val)
 
IO.puts ​"End of macro body, local = #{local}"
 
end
 
IO.puts ​"In macro definition, local = #{local}"
 
result
 
end
 
end
 
defmodule​ Test ​do
 
require​ Scope
 
 
local = 123
 
Scope.update_local(​"cat"​)
 
IO.puts ​"On return, local = #{local}"
 
end

Here’s the result of running that code:

 
In macro definition, local = some value
 
End of macro body, local = cat
 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required