Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

julia introspection - get name of variable passed to function

Tags:

julia

In Julia, is there any way to get the name of a passed to a function?

x = 10
function myfunc(a)
# do something here
end
assert(myfunc(x) == "x")

Do I need to use macros or is there a native method that provides introspection?

like image 366
ejang Avatar asked Oct 03 '15 23:10

ejang


People also ask

Is Julia pass by value?

In Julia, values are passed and assigned by reference.

What is :: In Julia?

A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .

Does Julia have methods?

Method TablesEvery function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table.

What is Julia exclamation mark?

an exclamation mark is a prefix operator for logical negation ("not") a! function names that end with an exclamation mark modify one or more of their arguments by convention.


1 Answers

You can grab the variable name with a macro:

julia> macro mymacro(arg)
           string(arg)
       end

julia> @mymacro(x)
"x"

julia> @assert(@mymacro(x) == "x")

but as others have said, I'm not sure why you'd need that.

Macros operate on the AST (code tree) during compile time, and the x is passed into the macro as the Symbol :x. You can turn a Symbol into a string and vice versa. Macros replace code with code, so the @mymacro(x) is simply pulled out and replaced with string(:x).

like image 109
Tom Breloff Avatar answered Sep 18 '22 15:09

Tom Breloff