Is there simple Julia syntax for assigning to a variable only if it is undefined (or falsy)? I mean something like Ruby's x ||= NEW_VALUE
. I have tried x || x=NEW_VALUE
but it throws an error. Barring easy syntax, what function can I use to check if a variable is defined?
15
votes
2 Answers
30
votes
4
votes
I've prepared a macro to deal with that little inconvenience.
macro ifund(exp)
local e = :($exp)
isdefined(Main, e.args[1]) ? :($(e.args[1])) : :($(esc(exp)))
end
Then in REPL:
julia> z
ERROR: UndefVarError: z not defined
julia> @ifund z=1
1
julia> z
1
julia> z=10
10
julia> @ifund z=2
10
julia> z
10
An example of interpolation:
julia> w
ERROR: UndefVarError: w not defined
julia> w = "$(@ifund w="start:") end"
"start: end"
julia> w
"start: end"
But, remember of the scope (y
is in the scope of for-loop):
julia> y
ERROR: UndefVarError: y not defined
julia> for i=1:10 y = "$(@ifund y="") $i" end
julia> y
ERROR: UndefVarError: y not defined
Let me know if it works. I'm curious, because it's my first exercise with macros.
edited: Julia v1.0 adaptation done.