[Haskell-cafe] Why are && and || right-associative?
Joachim Durchholz
jo at durchholz.org
Sat Apr 13 12:25:02 UTC 2019
Am 13.04.19 um 01:16 schrieb Viktor Dukhovni:
>> On Apr 12, 2019, at 3:15 PM, Joachim Durchholz <jo at durchholz.org> wrote:
>>
>> What is the basis for this expectation?
>> My expectation would be left associativity, just because I read stuff from left to right, and left associativity is what I get if I mentally parse from left to right.
>> So I'm curious what thought process arrives at the opposite expectation.
>
> Since (&&) short-circuits on first failure, and (||) short-circuits on
> first success, right associativity is more intuitive:
>
> a && b && c == a && (b && c)
> a || b || c == a || (b || c)
>
> as each can stop immediately when `a` is respectively False or True.
> This matches the fact that (&&) is naturally strict in its first argument
> and and lazy in the second, which works well with currying.
I guess my intuition is more based on math, where associativity is an
irrelevant detail, then LR parsing, where left associativity requires
less stack work.
BTW I have a feeling that the LR parsing process is pretty natural: we
read symbols from left to right, mentally combining them into groups as
soon as possible so we can abstract away from individual symbols.
> Also consider that, for example, in "ghci":
>
> foldr (&&) True (replicate 100000000000 False)
>
> returns immediately, while:
>
> foldr (&&) True (replicate 100000000000 False)
>
> hangs, which clearly shows that right folds are the more
> natural way to combine these boolean operators.
That's a Haskellism.
Not that anything is wrong with that, of course :-)
> And reading left to right, *is* IMHO right associative! You
> see:
>
> a || ...
>
> and immediately process a, then move on to what follows.
No, you see
a || ...
but you don't process anything, there's just a and ||.
Then you see
a || b ...
but you still don't know what to do with that, because maybe the next
operator has higher precedence (maybe &&, maybe even + or *).
Then you see
a || b || ...
and now you can tick off the first three symbols:
whatever || ...
where somewhere back in your mind, whatever === a || b.
> When reading an English sentence, you don't have to reach
> the last word before you can start to make sense of the
> preceding words, for left associativity, try German...
>
> [ Oops! Never mind, perhaps that explains the difference
> in perspective. :-) :-) ]
Don't worry :-)
Though I don't think that natural language processing works at any
conscious level, so I don't think that that influence is too important.
I German were the main influence, I would have to insist on postfix btw.
More information about the Haskell-Cafe
mailing list