*My struggle with macros*
Lets code macro for increment, that should be fairly easy right?
x = 33
macro inc(x)
:(x = x + 1)
end
@show @inc x
> LoadError: UndefVarError: x not defined
Hmm, it's not so easy as I thought, I must be missing some very basic
knowledge, lets see whats happening inside. In docs they say* macroexpand*
should be used for debugging.
x = 33
macro inc(x) x end
@show macroexpand(@inc x)
macro inc(x) :x end
@show macroexpand(@inc x)
macro inc(x) :($x) end
@show macroexpand(@inc x)
> macroexpand(@inc(x)) = 33
> macroexpand(@inc(x)) = 33
> macroexpand(@inc(x)) = 33
>
Little confused : That didn't tell me anything... What type is *x *anyway?
x = 33
macro inc(x)
show(x)
x
end
@inc(x)
> :x
>
So it is a symbol. In that case, why "*macro inc(x) :x end*" evaluates as *"33"
*instead of "*:x*"??
...
After hour of playing with macros I finally realize how to make use of
*macroexpand()*.
x = 33
v = 3
w = :v
ex = :(:(w = w + 1))
macro inc(x)
:(:(x = x + 1))
end
@inc v
@show macroexpand(eval(ex))
> macroexpand(eval(ex)) = :(w = w + 1)
>
And I also realize that I need to use interpolation...
x = 33
v = 3
w = :v
ex = :(:($w = $w + 1))
macro inc(x)
:(:($x = $x + 1))
end
@show macroexpand(eval(ex))
> macroexpand(eval(ex)) = :(v = v + 1)
>
Oh, that looks very nice. That's exactly what I wanted. My macro should
work exactly in the same way, since x ~ w and eval() is called
automatically when the line is executed...
@show @inc v
> @inc(v) = :(33 = 33 + 1)
>
WOW, WTF?