在 Julia 中将变量名保存为字符串 [英] Save variable name as string in Julia
问题描述
在 Julia 0.4 中,我有一个名为 variablex 的变量,其中
In Julia 0.4 I have a variable called variablex where
in: variablex = 6
out: 6
in: typeof(variablex)
out: Int64
我想将变量的名称保存为字符串,因此我希望得到类似变量a"之类的内容,该变量将变量variablex"的名称存储为字符串.
I would like to save the variable's name as a string, so I'd like to end up with something like the variable 'a' below which stores the name of the variable 'variablex' as a string.
in: a = Name(variablex)
out: variablex
in: typeof(a)
out: ASCIIString
在上面的示例中,我刚刚编写了函数Name",它将变量的名称作为字符串返回.Julia 中是否存在与我上面想象的示例函数名称"相同的功能?
In the example above I have just made up the function 'Name' which returns the name of a variable as a string. Is there an existing function in Julia which does the same thing as my imaginary example function 'Name' above?
推荐答案
你可以使用这样的宏:
macro Name(arg)
string(arg)
end
variablex = 6
a = @Name(variablex)
julia> a
"variablex"
信用(以及更多详细信息):this 常见问题解答.
Credit (and more details): this SO Q&A.
更多细节/解释:来自 Julia 文档:
宏以表达式、文字或符号的形式接收参数
macros receive their arguments as expressions, literals, or symbols
因此,如果我们尝试使用函数(而不是宏)创建相同的效果,就会遇到问题,因为函数将其参数作为对象接收.然而,对于宏,variablex
(在本例中)作为符号传递(例如,相当于输入 :variablex
).而且,string()
函数可以作用于符号,将其转换为字符串.
Thus, if we tried create the same effect with a function (instead of a macro), we would have an issue, because functions receive their arguments as objects. With a macro, however, the variablex
(in this example) gets passed as a symbol (e.g. the equivalent to inputting :variablex
). And, the string()
function can act upon a symbol, transforming it into a, well, string.
简而言之,您可以将符号视为一种非常特殊的字符串类型,它绑定并指向特定对象.再次来自 Julia 文档:
In short version, you can think of a symbol as a very special type of string that is bound to and refers to a specific object. From the Julia documentation again:
符号是一个内部字符串标识符
A symbol is an interned string identifier
因此,我们利用了这样一个事实,即在 Julia 的基本代码中,宏的设置已经为我们提供了一种获取与给定变量关联的符号的现成方法(通过将该变量作为参数传递给宏),然后利用符号是一种特殊类型的字符串这一事实,将它们转换为更标准的字符串类型是相对简单的.
Thus, we take advantage of the fact that in Julia's base code, the setup for macros already provides us with a ready way to get the symbol associated with a given variable (by passing that variable as an argument to the macro), and then take advantage of the fact that since symbols are a special type of string, it is relatively straight-forward to then convert them into a more standard type of string.
有关 Julia 中符号的更详细分析,请参阅这个著名的 SO 问题:什么是一个符号"在朱莉娅?
For a more detailed analysis of symbols in Julia, see this famous SO Question: What is a "symbol" in Julia?
有关宏的更多信息,请参阅此 SO 问题:在 Julia 中,为什么 @printf 是宏而不是函数?
For more on macros, see this SO Question: In Julia, why is @printf a macro instead of a function?
这篇关于在 Julia 中将变量名保存为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!