Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'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

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?

like image 344
lara Avatar asked Aug 17 '16 01:08

lara


2 Answers

You can use a macro like this:

macro Name(arg)
   string(arg)
end

variablex  = 6

a = @Name(variablex)

julia> a
"variablex"

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

Edit: More Details / Explanation: From the Julia documentation:

macros receive their arguments as expressions, literals, or symbols

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.

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

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.

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?

like image 128
Michael Ohlrogge Avatar answered Sep 28 '22 20:09

Michael Ohlrogge


For Julia 1.0 and above:

macro name(arg)
    x = string(arg)
    quote
        $x
    end
end

usage:

a = @name variablex #macro syntax
a = @name(variablex) #called as a function
like image 38
longemen3000 Avatar answered Sep 28 '22 22:09

longemen3000