[Haskell-cafe] Precedence (Part 2)
greg at maptuit.com
Thu Apr 3 13:49:34 EDT 2008
PR Stanley <prstanley at ntlworld.com> writes:
> Hi folks
>> let f = sum.map (^2).filter even
>> f [1..4]
> So far so good!
>> sum.map (^2).filter even [1..4]
> returns an error.
> How is it that the composition above as part of a function equation
> doesn't return any errors while on its own it requires parentheses? I
> can understand the need for the parentheses - the composition operator
> takes two arguments/operand,s each of which is a mapping which must
> correspond to specific domain and range requirements i.e. (b->c ->
> (a->b) -> (a->c)
> Why aren't the parentheses required in the function definition?
The answer is precedence. The (.) operator is right-associative and has
lower precedence than function application, meaning that:
a . b . c . d . e == a . (b . (c . (d . e)))
so the second form is equivalent to:
sum . ((map (^2)) . (filter even [1..4]))
:t (filter even [1..4])
should give you your explanation.
If you want to avoid parentheses, you can write that expression as:
sum . map (^2) . filter even $ [1..4]
which really means
(sum . map (^2) . filter even) [1..4]
which is the same as "f [1..4]" above.
Hope that helps,
More information about the Haskell-Cafe