问题描述
限时送ChatGPT账号..这个问题纯粹是出于求知欲.
This question comes purely out of intellectual curiosity.
相对频繁地浏览 Python 部分后,我看到了许多类似于 this,有人要求以编程方式定义全局变量.他们中的一些人知道 exec
的陷阱,其他人则没有.
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.
不过,我最近一直在用 Stata 编程,其中常见的有以下几点:
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
}
在 Stata 中,创建了一个名为 N
的本地宏,N
的计算结果为 100.在 foreach
的每次迭代中循环,从x1
到x100
的值被分配给本地宏x
.然后,循环内的行将 i
的平方分配给 x
的展开,这是一个与 i
结尾相同的局部宏.也就是说,在这个循环之后,x4
扩展到 4^2,x88
扩展到 88^2.
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.
在 Python 中,做类似事情的方法是:
In Python, the way to do something similar would be:
squares = {}
for x in range(1,101):
squares[x] = x**2
那么 squares[7]
等于 7^2.
Then squares[7]
equals 7^2.
这是一个非常简单的例子.stata 宏还有很多其他用途.您可以将它们用作传递要评估的函数的方法,例如:
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
}
r
周围的双刻度线将该宏展开两次,首先是 r1
/r2
然后是 regress
/corr
,以y
为因变量,x
为自变量进行线性回归的结果,然后显示<代码>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.
我的问题基本上是,stata 是否属于更大的语言类别,其中变量赋值/评估采用这种宏赋值/扩展"形式?任何解释为什么会这样设计语言,和/或其他语言中类似结构的示例的奖励积分.
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.
这篇关于哪些类型的语言允许以编程方式创建变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论