Search code examples
juliasymbols

Outputting variable name and value in a loop


I want to loop over a list of variables nad output the variable name and value. E.g., say I have x=1 and y=2, then I want an output

x is 1
y is 2

I suspect I need to use Symbols for this. Here is my approach, but it isn't working:

function t(x,y)
    for i in [x,y]
        println("$(Symbol(i)) is $(eval(i))") # outputs "1 is 1" and "2 is 2"
    end
end

t(1, 2)

Is there a way to achieve this? I guess a Dictionary would work, but would be interested to see if Symbols can also be used here.


Solution

  • One option is to use a NamedTuple:

    julia> x = 1; y = 2
    2
    
    julia> vals = (; x, y)
    (x = 1, y = 2)
    
    julia> for (n, v) ∈ pairs(vals)
               println("$n is $v")
           end
    x is 1
    y is 2
    

    Note the semicolon in (; x, y), which turns the x and y into kwargs so that the whole expression becomes shorthand for (x = x, y = y).

    I will also add that your question looks like like you are trying to dynamically work with variable names in global scope, which is generally discouraged and an indication that you probably should be considering a datastructure that holds values alongside labels, such as the dictionary proposed in the other answer or a NamedTuple. You can google around if you want to read more on this, here's a related SO question:

    Is it a good idea to dynamically create variables?