Search code examples
functionhaskellfunction-call

Brackets in Haskell function call


I'm struggling to remember how to use brackets when calling Haskell functions. I come from a C-style background and I'm used to f(comma, separated, args) syntax for calling functions. Apparently this is the same as (in Haskell) ((((f) comma) separated) args) but this is just confusing.

Why do I need all these brackets?


Solution

  • It's easy to remember the rules regarding parentheses and function calls in Haskell: there aren't any, because parentheses have nothing to do with function calls!

    The basic syntax for function calls in Haskell is to just write terms next to each other: function argument is calling function, passing it argument. In C-like syntax you'd write that as function(argument). Your C example f(comma, separated, args) would be written in Haskell as f comma separated args.

    Haskell uses parentheses only in the way they are used in high school mathematics: for grouping sub-expressions so that you get a different call structure. For example, in maths 1 + 2 * 3 would call * on 2 and 3, and call + on 1 and the result of the * call. (1 + 2) * 3 changes the grouping so that + is called on 1 and 2, and * called on that result and 3. The same is valid Haskell (and C), with the same meaning, but parentheses with grouping like this can also be useful to group expressions with ordinary functions rather than infix operators. For example f comma separated args calls f on the arguments comma, separated, and args, while f comma (separated args) means to call separated passing it args, and call f passing it comma and the result of the call to separated.

    There is no need for ((((f) comma) separated) args); in fact you would have seen that as an explanation of how f comma separated args is recognised by the language when you use no parentheses. It's wrapping every sub-expression in explicit parentheses so there's no ambiguity to show you what the default is, not saying you actually need all those parentheses.