使用元编程在 Julia 中声明顶级变量 [英] Declaring top level variables in Julia using metaprogramming

查看:11
本文介绍了使用元编程在 Julia 中声明顶级变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用元编程回答这个问题,但是for的范围规则循环导致我的变量没有在最上层(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 中声明顶级变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆