Parentheses in a Haskell function call
I am trying to remember how to use parentheses when calling Haskell functions. I am coming from a C style background and I am using syntax f(comma, separated, args)
to call functions. This appears to be the same as (in Haskell) ((((f) comma) separated) args)
, but it's just confusing.
Why do I need all these brackets?
source to share
If you are used to the c-style function call syntax, then for a c-style function like
// defining the function
int plus(int a, int b)
{
return a + b;
}
// elsewhere, calling the function
plus(a, b); // brackets surrounding only the arguments, comma separated
Then the equivalent Haskell code would be
-- defining the function
plus :: Int -> Int -> Int
plus a b = a + b
-- elsewhere, calling the function:
(plus a b) -- brackets surrounding the function and the arguments, no commas
To use an example in your question,
f(comma, separated, args);
This will be equivalent to
(f comma separated args)
But these parentheses are not needed unless the function call is embedded in another expression. In haskell, this is also equivalent to
((((f) comma) separated) args)
but those extra parentheses are not needed either, they just emphasize how Haskell views function application (where each function technically takes only one argument); so this last case would be like the following function call c:
f(comma)(separated)(args);
source to share
It's easy to remember the rules about parentheses and function calls in Haskell: there are none, because there is nothing in parentheses for function calls!
The basic syntax for function calls in Haskell is to just write terms next to each other: function argument
calls function
by passing it in argument
. In C-like syntax, you have to write it like function(argument)
. Your C example f(comma, separated, args)
would be written in Haskell as f comma separated args
.
Haskell only uses parentheses as they are used in high school math: to group subexpressions to get a different calling structure. For example, in math 1 + 2 * 3
let's call *
on 2 and 3 and call +
on 1 and call result *
. (1 + 2) * 3
changes the grouping so that it +
is called on 1 and 2, and *
calls this result and 3. The same is true for Haskell (and C) with the same meaning, but parentheses with this grouping can also be useful for grouping expressions with regular functions not with infix operators. For example, f comma separated args
calls the f
arguments comma
, separated
and args
, and f comma (separated args)
means the call separated
passing it args
and the call f
passing itcomma
> and the call result separated
.
No need for ((((f) comma) separated) args)
; in fact you would see it as an explanation of how the f comma separated args
language recognizes when using no parentheses . It wraps each subexpression in explicit parentheses, so there is no ambiguity to show you what the default is, rather than tell you that you really need all those parentheses.
source to share