This question comes purely out of intellectual curiosity.
Having browsed the Python section relatively often, I've seen a number of questions similar to this, where someone is asking for a programmatic way to define global variables. Some of them are aware of the pitfalls of exec
, others aren't.
However, I've recently been programming in Stata, where the following is common:
local N = 100
local i = 1
foreach x of varlist x1 - x`N' {
local `x' = `i' * `i'
++i
}
In Stata parlance, a local macro with the name N
is created, and N
evaluates to 100. In each iteration of the foreach
loop, a value from x1
to x100
is assigned to the local macro x
. Then, the line inside the loop, assigns the square of i
to the expansion of x
, a local macro with the same ending as i
. That is, after this loop x4
expands to 4^2 and x88
expands to 88^2.
In Python, the way to do something similar would be:
squares = {}
for x in range(1,101):
squares[x] = x**2
Then squares[7]
equals 7^2.
This is a pretty simple example. There are a lot of other uses for stata macros. You can use them as a way to pass functions to be evaluated, for example:
local r1 "regress"
local r2 "corr"
foreach r of varlist r1-r2 {
``r'' y x
}
The double tickmarks around r
expand that macro twice, first to r1
/r2
then to regress
/corr
, with the result of running a linear regression with y
as the dependent and x
as the independent variable, and then showing the correlation between y
and x
. Even more complex stuff is possible.
My question is basically, does stata fall into some larger category of languages where variable assignment/evaluation takes this form of "macro assignment/expansion"? Bonus points for any explanation of why a language would be designed like this, and/or examples of similar constructs in other languages.
It's really just a question of how much syntactic sugar is there. In any language worth its salt, you can use a map or dictionary data structure to create variable names (keys) at runtime with some value. Some languages may more transparently integrate that with ordinary variable identifiers than others.