I'm trying to write a simple swap!
macro in Julia, to understand the macro system. Here's my code so far:
macro swap!(x, y)
quote
local tmp = $(esc(y))
$x = $(esc(y))
$y = tmp
end
end
a = 1
b = 2
@swap!(a, b)
# prints: a: 1, b: 2
println("a: $a, b: $b")
This runs without error, but isn't actually changing the values. Julia doesn't seem to have a function that just expands macros without executing them (as far as I can see), so this is hard to debug.
The equivalent quote in a REPL seems to work as expected:
julia> a = 1
1
julia> a_sym = :a
:a
julia> a_sym
:a
julia> b = 2
2
julia> b_sym = :b
:b
julia> eval(quote
tmp = $a_sym
$a_sym = $b
$b_sym = tmp
end)
1
julia> a
2
julia> b
1
What am I doing wrong?
a, b = b, a
assignment isn't enough? – juliohmmacroexpand(:(@swap x, y))
– Jeremy Wall