Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign only if not already defined in Julia

Tags:

julia

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?

like image 991
Sean Mackesey Avatar asked Dec 10 '13 00:12

Sean Mackesey


People also ask

How do you check if a function call is valid in Julia?

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.

How to determine the declared type of a field in Julia?

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.

Can I redefine built-in constants and functions in Julia?

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:

How do you name a variable in Julia?

"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!"


2 Answers

You can use the @isdefined macro: (@isdefined x) || (x = NEW_VALUE).

like image 179
StefanKarpinski Avatar answered Oct 10 '22 12:10

StefanKarpinski


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.

like image 28
Maciek Leks Avatar answered Oct 10 '22 14:10

Maciek Leks