Question

I would like to be able to assign values to variables in Julia through a simple string loop.

For instance:

x1, x2, x3, x4 = 14, 12, 34, 19
letters = "abcd"

for i in 1:4
  val = get("x$i")
  var = letters[i]
  assign(var, val)
end

a
14

Note, I choose the function "assign" and "get" because I am used to them in R.

The reason I want to do this is because I have a function which takes multiple arguments which are all evaluated identically and I figured there was no point duplicating code. Something like:

function f(a,b,c,d) 

  if a<0 a==-9999 end
  if b<0 b==-9999 end
  if c<0 c==-9999 end
  if d<0 d==-9999 end

end

Of course the functions that I am applying to each is really much longer than a simple recode command.

I guess I could do something like this:

function f(a=1,b=2,c=3,d=4, p=[a,b,c,d])
    for (i in 1:4)
        if p[i]<0
            p[i]=-9999
        end
    end
    sum(p)
end

However, this creates other problems with "set index" which is something I will need to read up more on. Thanks for your consideration! Francis

Was it helpful?

Solution

After your second suggestion for what to do, I figure you might actually want something like this.

function f(args...)
    acc = zero(args[1])
    for a in args
        if a < 0
            acc -= 9999
        else
            acc += a
        end
    end
    acc
end

Usage is just like

OTHER TIPS

This does the trick:

x1, x2, x3, x4 = 14, 12, 34, 19
letters = "abcd"

for i  in 1:4
    assignment = parse("$(letters[i]) = x$(i)")
    eval(assignment)
end

You can read about the parse function, which turns strings into expressions, here: http://julia.readthedocs.org/en/latest/stdlib/base/#Base.parse

To do this kind of weird dynamic variable trixing in Julia, you have to use macros and metaprogramming. The gist of it is a very powerful interface to code generation. I think it would be possible to write a macro that does the same as the above code on the form

x1, x2, x3, x4 = 14, 12, 34, 19
@assign("abcd", 1:4)

and translates that "compile time" to

x1, x2, x3, x4 = 14, 12, 34, 19
begin
    a = x1
    b = x2
    c = x3
    d = x4
end

It will take me some time to write and debug such a macro. Can you describe your use case, so I can see if there are some constraints that are actually not important, or more functionality you'd like? The 1:4 for example seems redundant as I can just use for (i, letter) in enumerate("abcd") to get the same loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top