Truthiness and short circuit or

…based on a made up story:
Somewhere in the cold, dark code

>a = true && "scam"

The greedy novice wonders trough the code and asks:

>a == false
false

…so a must true. Sweet!

try
    if a 
        println("send me a billion dollars")
    end
catch e
   "You got scammed!"
end

…waiting to be rich…

"You got scammed"

Whaaaat!?

I have seen that the functionality of the short circuit boolean operators have been discussed for many years (an old discussion), but given all the high-and-mighty talk about no truthinesses in Julia I was (as a newbie) surprised to find that the first statement above did not return an error…

I guess this is more of comment than a question…

1 Like

Well, you’re abusing try/catch to “use” a non-boolean variable as if it were a boolean. Without that, you would have seen the error telling you it wasn’t a boolean in the if statement.

2 Likes

What did any of this have to do with truthiness and why would the greedy novice not just print the value of a?

1 Like

Except… it does! You just caught and ignored it. Don’t do that (and similarly, don’t do things like if a == true).

1 Like

The following three Julia expressions are essentially equivalent:

x = a && b && c

x = a ? (b ? c : b) : a

x = if a
    if b
        c
    else
        b
    end
else
    a
end

In particular, notice that c is never treated as a boolean. It is simply the value of the expression if a and b are true. You can also observe this in

julia> true && 1 && 2 # 1 isn't a Bool
ERROR: TypeError: non-boolean (Int64) used in boolean context

julia> false && 1 && 2 # never tries to never evaluate 1 as a Bool
false
1 Like

I’m quite fond of the ternary operator version because it’s both terse and easily translatable to

Is a true? If so, if b is true, you have c, but if it’s not you still have just a.

Except that c may be true even if b is not. Too bad we don’t have a naive set theory operator to express c <=> b.