Skip to content

Operator precedence of & and | is surprising as element-wise boolean operators #5187

@mbauman

Description

@mbauman

I just got bit by the python-like operator precedence for the operators | and &. As bitor and bitand, it's a wonderful choice (making checking for bit flags much simpler — a common gotcha in C).

But when behaving as their element-wise boolean counterparts to || and &&, it is surprising. A < 1 || A > 2 must be written differently if A is an array: (A .< 1) | (A .> 2). Perhaps all that's needed here is a bit more documentation (i.e., putting https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm#L1-L19 into the Mathematical Operators page, or as something to mention to users coming from Matlab).

But as I look at the source for |(::StridedArray,::StridedArray), I see that it's actually applying the bitwise operator to all elements. As a radical alternative, what about adding .&& and .|| with similar precedence to && and || that ensures boolean elements? Functionally, & and .&& would behave the same on logical arrays, but they'd each have the precedence one would expect in each context. (Of course, there'd still be some cognitive dissonance here as the elementwise boolean operators couldn't short-circuit like their scalar equivalents).

Metadata

Metadata

Assignees

Labels

breakingThis change will break codeneeds decisionA decision on this change is neededparserLanguage parsing and surface syntax

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions