Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring top level variables in Julia using metaprogramming

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)

like image 289
JKnight Avatar asked Sep 27 '14 04:09

JKnight


1 Answers

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

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

This code can also be trivially adapted into a macro (but then it does need esc).

like image 166
simonster Avatar answered Oct 05 '22 06:10

simonster