gdkrmr
May 22, 2017, 10:54am
1
is the last line intended behaviour?
julia> false || println("Here")
Here
julia> true || println("Here")
true
julia> false && println("Here")
false
julia> true && println("Here")
Here
julia> true && false || println("Here")
Here
julia> false && true || println("Here")
Here
The expression in parantheses evaluates to false
. I think this is intended.
Its documented here: https://docs.julialang.org/en/stable/manual/control-flow/#short-circuit-evaluation
Specifically this:
Both &&
and ||
associate to the right, but &&
has higher precedence than ||
does.
Per
May 22, 2017, 11:49am
4
In many programming languages, including Julia, &&
has higher precedence than ||
.
Other programming languages, like bash, give these operators equal precedence, so the result would be different.
Some style guides recommend using parentheses in expressions involving both &&
and ||
, to help the uncertain reader.
gdkrmr
May 22, 2017, 12:57pm
5
so if &&
and ||
are right-associative, then why does the following not print anything, shouldn’t true && println("Here")
get evaluated first?
julia> false && true && println("Here")
false
julia> parse("""false && true && println("Here")""")
:(false && (true && println("Here")))
The compiler is very smart.
function f()
false && true && println("Here")
end
julia> @code_warntype f()
Variables:
#temp#
Body:
begin
return $(QuoteNode(false))
end::Bool
right-associative means that :(A && B && C)
parses as :(A && (B && C))
(as opposed to :((A && B) && C)
). A
is evaluated first because these expressions are evaluated left-to-right in Julia, and since it’s false, the whole expression is known to be false and there’s no need to evaluate the rest of it.
1 Like