Save variable name as string in Julia

In Julia 0.4, I have a variable called variablex, where

in: variablex = 6 out: 6 in: typeof(variablex) out: Int64 

I would like to save the variable name as a string, so I would like to get something like the variable "a", below which the variable name "variablex" is stored as a string.

 in: a = Name(variablex) out: variablex in: typeof(a) out: ASCIIString 

In the above example, I just made up the Name function, which returns the variable name as a string. Does Julia have an existing function that does the same thing as my imaginary name function above?

+5
source share
1 answer

You can use the macro as follows:

 macro Name(arg) string(arg) end variablex = 6 a = @Name(variablex) julia> a "variablex" 

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

Edit: Details / Explanation: From Julia's documentation :

macros get their arguments as expressions, literals or characters

Thus, if we tried to create the same effect using a function (instead of a macro), we will have a problem because the functions will receive their arguments as objects. However, with the macro, variablex (in this example) is passed as a character (for example, the equivalent of input :variablex ). And the string() function can act on a character, converting it to a string, well ,.

In the short version, you can think of a character as a very special type of string that is bound to and relates to a specific object. From Julia's doc:

The character is the intern string identifier

Thus, we use the fact that in the Julia base code, the macro setting already provides us with a ready-made way to get the character associated with this variable (passing this variable as an argument to the macro), and then use the fact that, since the characters are special string type, relatively straightforward, to convert them to a more standard string type.

For a more detailed analysis of the characters in Julia, see this famous SO question: What is the character "in Julia?"

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

+9
source

All Articles