Reputation: 25842
I always have troubles to place parenthesis in OCaml. Well, I always don't want to, but sometimes get error.
for example, let's say I have two functions:
let f_a x y = x+y
and let f_b x = x+1
.
If I do f_a 3 f_b 4
, I can't and I should do f_a 3 (f_b 4)
.
But if I do f_a 3 * f_b 4
, it is perfectly fine.
Another example, If I do f_a x y::[]
, it is fine too and I don't need to add parenthesis like this (f_a x y)::[]
.
Also I find that I don't need parenthesis for elements inside a tuple: (f_a 1 2, f_b 3)
is fine.
So can anyone teach me the general rules to decide when using parenthesis and when not?
Upvotes: 3
Views: 2827
Reputation: 36031
Here's a table explaining the precedence and associativity of certain expressions in OCaml.
As you can see from there, function application is left-associative, meaning that f_a 3 f_b 4
is interpreted as (((f_a) 3) f_b) 4
. However, multiplication (*
) has lower precedence than function application, which means that f_a 3 * f_b 4
is interpreted as (f_a 3) * (f_b 4)
(first applying functions, afterwards multiplication).
Last, ::
has a lower precedence than function application, so f_a x y::[]
first applies the function, and afterwards concatenates to the empty list (i.e. "consumes" ::[]
). This means that f_a x y::[]
is seen as (f_a x y)::[]
.
Unfortunately, I could not deduce a simple rule of thumb, but I always remember that "function application has a quite high precedence and is left-associative". This works quite well for me.
Upvotes: 6
Reputation: 122489
Parentheses are simply to group things so they are evaluated as one whereas without parentheses they may or may not be due to operator precedence. Function application has higher precedence than all normal operators. You can see the OCaml precedence table by going here and then scrolling up a little.
Upvotes: 2