Parenthesizing conditions

The Julia Style Guide says:

Don’t parenthesize conditions …Write:

if a == b

instead of:

if (a == b)

However, I recently discovered a potentially dangerous characteristic of Julia, which, as far as I know, can only be prevented by parenthesizing conditions. Starting with this simple or statement:

julia> true | false
true

Everything is working as expected. However, if we replace true and false with conditions that return true and false, respectively, the or statement now returns false:

julia> 1==1 | 1==2
false

Putting the conditions in parentheses is uglier, but fixes the problem:

julia> (1==1) | (1==2)
true

For comparison, MATLAB returns true for all of the above situations. Here’s the MATLAB:

>> true | false
ans =
  logical
   1
>> 1==1 | 1==2
ans =
  logical
   1
>> (1==1) | (1==2)
ans =
  logical
   1

My question: What’s the appropriate way to deal with conditionals? Ignore the Style Guide, or is there some other way to write conditionals that’s less prone to error or misinterpretation?

Using logical or instead of bit wise or ‘fixes’ it, too:

julia> 1==1 || 1==2
true

But you got a point: a potential trap.

If this were the condition it would be written as

if (1==1) | (1==2)

instead of

if ((1==1) | (1==2))

so I don’t see the discrepancy. What you highlighted is a matter of order of operations.

4 Likes

I believe the style guide refers to an outer pair of parentheses, which is a required part of the if statement in some programming languages but unnecessary in Julia. You shouldn’t be afraid of using semantically significant or clarifying parentheses. I.e., the style guide is fine with

if (1 == 1) | (1 == 2)

but advises against

if ((1 == 1) | (1 == 2))
3 Likes