[Haskell-cafe] Why is $ right associative instead of left
associative?
Brian Hulley
brianh at metamilk.com
Sat Feb 4 13:02:30 EST 2006
Tomasz Zielonka wrote:
> On Sat, Feb 04, 2006 at 02:52:20PM -0000, Brian Hulley wrote:
>> Hi -
>> In the Haskell98 report section 4.4.2 $ is specified as being right
>> associative. This means that f $ a0 a1 $ b0 b1 would parse as f (a0
>> a1 (b0 b1)) which seems rather strange to me. Surely it would be
>> much more useful if $ were defined as left associative so that it
>> could be used to separate the args to f?
>>
>> Does anyone know why this strange associativity was chosen?
>
> Probably it was anticipated that right associative version will
> be more useful. You can use it to create a chain of transformations,
> similar to a chain of composed functions:
>
> (f . g . h) x = f $ g $ h $ x
>
> Example:
>
> map f $ group $ sort $ filter g $ l
>
> But of course, left associative version can also be useful. Some
> time ago I used a left associative version of the strict application
> operator, which I named (!$).
I wonder if anyone has done empirical studies to determine scientifically
which associativity would be more useful in practice eg by analysis of
source code involving $ and comparing the number of parentheses that would
be needed in each case, and perhaps also some studies involving the number
of confused readers in each case...
Even though both versions are useful, it seems to me that faced with the
choice of choosing an associativity for an operator that does function
application, and given that prefix application is left associative, there is
one clear winner, but unfortunately the Haskell committee didn't see it this
way, and perhaps it is too late to ever change this (just like :: and :
which were mixed up for reasons unknown). Especially since chains can
already be composed using "." .
>
> Anyway, you can't always remove all parentheses. And why would you
> want to? Everybody is used to them.
$'s advertised purpose is to remove parentheses, but I agree that
parenthesized code is often more readable (especially when operators have
unexpected fixities... :-))
Regards, Brian.
More information about the Haskell-Cafe
mailing list