[Haskell-cafe] Precedence of plus and bit-wise-and

Richard A. O'Keefe ok at cs.otago.ac.nz
Wed Aug 16 05:54:47 UTC 2017



On 16/08/17 12:07 PM, Levent Erkok wrote:
> I was surprised today to find that C and Haskell differ on the
> precedence of addition and bit-wise and.
>
> In Haskell, bit-wise-and (.&.) binds tighter. In C, it's the other way
> around.

It is worth noting that Haskell uses a different symbol (.&.) than
C (&), so it's not altogether surprising.

There is no generally accepted convention.
In Erlang, bitwise and has the same precedence as *
        and bitwise or  has the same precedence as + .
In Standard ML, andb and orb are not operators at all.
In Fortran, iand and ior are not operators at all.
The & and | operators in PL/I are wider scope than the
arithmetic and comparison operators, but they do double
duty for bitwise operations and conditional operations,
just as BCPL did.
In Prolog, bitwise and and or have the same precedence as
as + and thus as each other.
In Ada, 'and' and 'or' have the same precedence as each
other, wider scope than comparisons, and the language
does not allow you to mix 'and' and 'or' without parentheses.
In Pascal, the bitwise operators are actually called * and +.
In Smalltalk, "bitAnd:" and "bitOr:" have the same
precedence as each other, wider scope than "+" and "*"
(which have the same precedence as all binary selectors).
Not that Smalltalk technically _has_ operator precedence...
SETL2 doesn't appear to have bitwise operations at all.

I could go on, but I think I've made the point that expecting
everything to be just like C is rather risky.  For that
matter, common advice for C programmers is "never mix
arithmetic and bitwise operators without parentheses".

>
> While I like Haskell's precedence better, this was a gotcha; and I
> wondered if this behavior is documented somewhere. I looked through the
> Haskell wiki, but couldn't find anything pertinent.
>
> Discrepancies are always problematic.

The only language in which you will not find discrepancies
with C is C itself, and I'm afraid you will find (semantic)
discrepancies there.  If I went around complaining that C
doesn't look enough like APL, what good would that do me?



More information about the Haskell-Cafe mailing list