Interpolate all variables in expression without using $ for each variable

Hi,

is there any alternative way to do this:

x = 1
y = 2
z = 3
i = 1
j = 2
k = 3
expr = :($x + 2 * $y + $z + $i + $j + $k)

For example, something like:

expr = @$ :(x + 2 * y + z + i + j + k)

Thanks!

Expr(:call, :+, x, y, z, i, j, k)
2 Likes

Thanks for your reply!

I am trying to make it more readable by removing the $s. Your suggestion is not more readable than just using the dollar signs.

For example, the expression I am actually trying to build is:

expr = :($du[1] = $κ * $θ * $b + ($σ^2) / 2 * $α * ($b^2))

And your suggestion is to write the following

Expr(:(=), (:ref, du, 1), (:call, :+, (:call, :*, κ, θ, b), (:call, :*, (:call, :/, (:call, :^, σ, 2), 2), 1, (:call, :^, b, 2))))

which is not more readable.

Thanks!

For your use, stick with the $s. It has the advantage of being easily understood by others. Even if nobody else would ever see the source, you may write other, more shared code that uses the same approach (I have found that being consistent with Julia techniques makes for faster writing of correct code over time).

Why are you trying to do this? What problem are you trying to solve that involves interpolating lots of variables into lots of expressions?

3 Likes

Hi. Please, look at my reply to @fredrikekre.

You didn’t really explain your underlying problem. Why are you building lots of expressions like this, so many that you want a special syntax? Are you passing expressions around when you really should be passing functions?

5 Likes