Access the name and value by using a symbol

question

#1

I wonder if it is possible to get the value and the name by using a symbol. I mean something like this (which does not work):

julia> x = 1
       y = :x 
       println("$y is equal to $(getvalue(y))") 
x is equal to 1

What I want is basically provide an array of symbols and store the Pair(name, value) as a dictionary (or named tuple).

Thanks


#2

Is this what you are looking for?

println("y is equal to $(eval(y))")

#3

It is very close, but is there a way to do in in local scope?

x = 1

function f()
	x = 2
	y = :x
	println("y is equal to $(eval(y))")
end

f()

prints: y is equal to 1


#4

I’m pretty sure there is no way, and I’m also pretty sure that this is by design. In order to be able to compile functions, some restrictions need to be imposed on local scopes, such as no eval into the local scope of the function. I think this falls into the same category. Just just a dict.


#5

Yeah, I actually thought it already but it was just i can I missed some concepts of meta-programming.

Thank you for replies.


#6

The problem is that eval always executes in global scope (or a module), I am not sure if the following helps you:

macro p(s)
    @assert s.head == Symbol("=")
    y = string(s.args[1])
    _y = s.args[1]
    x = s.args[2].value
    quote
        $(esc(_y)) = $(esc(x))
        println($y, " is equal to ", $(esc(x)))
    end
end

function f()
    x = 2
    @p y = :x
    y
end
f()

Edit: Fixed bug in assignment of y


#7

Ok, this is a possibility but I think I will overcome this issue by using other ideas in my code. Thanks anyway.


#8

I suggest you look at the Cartesian section in the manual for inspiration, e.g. @nextract:

https://docs.julialang.org/en/stable/devdocs/cartesian/#Base.Cartesian.@nextract