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?
For example, to check that a macro was passed a function call expression, you might use isexpr (ex, :call). Return whether the symbol or string s contains characters that are parsed as a valid identifier in Julia code.
Determine the declared type of a field (specified by name or index) in a composite DataType T. The declared types of all fields in a composite DataType T as a tuple. This function requires at least Julia 1.1. Get the number of fields that an instance of the given type would have. An error is thrown if the type is too abstract to determine this.
Julia will even let you redefine built-in constants and functions if needed (although this is not recommended to avoid potential confusions): However, if you try to redefine a built-in constant or function already in use, Julia will give you an error:
"Hello World!" Julia provides an extremely flexible system for naming variables. Variable names are case-sensitive, and have no semantic meaning (that is, the language will not treat variables differently based on their names). julia> x = 1.0 1.0 julia> y = -3 -3 julia> Z = "My string" "My string" julia> customary_phrase = "Hello world!"
You can use the @isdefined
macro: (@isdefined x) || (x = NEW_VALUE)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With