问题描述
我想使用元编程来回答这个问题,但是对于循环导致我的变量未在最高(REPL)范围内定义:
I want to answer this question using metaprogramming, but the scoping rules of for loops are causing my variables to not be defined in the upper-most (REPL) scope:
for x = [:A1, :A2]
@eval x = rand(2,2)
end
我知道可能有一个简单的解决方法,但是我周五晚上的脑子想不起来.你们其中一个元编程迷可以帮助我找到一个简洁的解决方案吗? (我意识到宏可能可以转义,但我想考虑更短的内容)
I know there's probably an easy way around this, but my Friday night brain can't think of one. Can one of you metaprogramming junkies help me find a succinct solution? (I realize a macro might work with escaping, but I'm trying to think of something shorter)
推荐答案
如果只想在全局范围内定义变量,则只缺少$
:
If you only want to define the variables in the global scope, you're just missing a $
:
for x = [:A1, :A2]
@eval $x = rand(2,2)
end
但是,即使将@eval
放在函数中,也总是在顶级对其进行评估.如果要在函数作用域中定义变量,则需要将整个函数放在@eval
中,构造代码块,并将其插值到函数中:
But @eval
is always evaluated at top level even if you put it inside a function. If you want to define the variables in a function scope, you need to put the entire function inside @eval
, construct the code block, and interpolate it into the function:
@eval function f()
...
$([:($x = rand(2, 2)) for x in [:A1, :A2]]...)
...
end
此代码也可以微不足道地改编成宏(但随后确实需要esc
).
This code can also be trivially adapted into a macro (but then it does need esc
).
这篇关于使用元编程在Julia中声明顶级变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!