朱莉娅掉期有什么问题!宏? [英] What's wrong with this Julia swap! macro?
问题描述
我正在尝试在Julia中编写一个简单的swap!
宏,以了解宏系统.到目前为止,这是我的代码:
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.
REPL中的等效引号似乎可以正常工作:
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
我在做什么错了?
推荐答案
I think you probably want something like below but are getting messed up by hygiene. The trick is to escape correctly.
macro swap(x,y)
quote
local tmp = $(esc(x))
$(esc(x)) = $(esc(y))
$(esc(y)) = tmp
end
end
这是展开后的样子
julia> macroexpand(quote @swap(x,y) end)
quote # none, line 1:
begin # none, line 3:
local #189#tmp = x # line 4:
x = y # line 5:
y = #189#tmp
end
end
效果
julia> x
1
julia> y
2
julia> @swap(x,y)
julia> x
2
julia> y
1
通过对比,您的宏正确地在一个赋值中转义了y,但在其他2条语句中未转义,因此设置了引入变量的值,而不是预期的x和y.
By contrast your macro escapes y in one assignment correctly, but not in the other 2 statements and so sets the values of introduced variables rather than the intended x and y.
julia> macroexpand(quote @swap!(x,y) end)
quote # none, line 1:
begin # none, line 3:
local #208#tmp = y # line 4:
#209#x = y # line 5:
#210#y = #208#tmp
end
end
这篇关于朱莉娅掉期有什么问题!宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!