在Julia中将变量名称另存为字符串 [英] Save variable name as string in Julia

查看:78
本文介绍了在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'的形式结束,该变量下方的变量'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

在上面的示例中,我刚刚组成了函数名称",该函数以字符串形式返回变量的名称. 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"

信用(以及更多详细信息):常见问题解答

Credit (and more details): this SO Q&A.

更多详细信息/说明:来自朱莉娅文档:

宏将其参数作为表达式,文字或符号接收

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?

有关宏的更多信息,请参见以下问题:

For more on macros, see this SO Question: In Julia, why is @printf a macro instead of a function?

这篇关于在Julia中将变量名称另存为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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