Search code examples
functionhaskelloperator-keywordoperator-precedence

Haskell operator vs function precedence


I am trying to verify something for myself about operator and function precedence in Haskell. For instance, the following code

list = map foo $ xs

can be rewritten as

list = (map foo) $ (xs)

and will eventually be

list = map foo xs

My question used to be, why the first formulation would not be rewritten as

list = (map foo $) xs

since function precedence is always higher than operator precedence, but I think that I have found the answer: operators are simply not allowed to be arguments of functions (except of course, if you surround them with parentheses). Is this right? If so, I find it odd, that there is no mention of this mechanic/rule in RWH or Learn you a Haskell, or any of the other places that I have searched. So if you know a place, where the rule is stated, please link to it.

-- edit: Thank you for your quick answers. I think my confusion came from thinking that an operator literal would somehow evaluate to something, that could get consumed by a function as an argument. It helped me to remember, that an infix operator can be mechanically translated to a prefix functions. Doing this to the first formulation yields

($) (map foo) (xs)

where there is no doubt that ($) is the consuming function, and since the two formulations are equivalent, then the $ literal in the first formulation cannot be consumed by map.


Solution

  • You are correct. This rule is part of the Haskell syntax defined by the Haskell Report. In particular note in Section 3, Expressions, that the argument to function application (an fexp) must be an aexp. An aexp allows operators as part of sections, and also within a parenthesized expression, but not bare operators.

    In map foo $ xs, the Haskell syntax means that this is parsed as two expressions which are applied to the binary operator $. As sepp2k notes, the syntax (map foo $) is a left section and has a different meaning.

    I have to confess I've never thought much about this and actually had to look it up in the Report to see why operators have the behavior they do.