shplaz
shplaz

Reputation: 77

Why do these addition statements produce different results in ocaml?

All the documentation I can find for OCAML agrees that the "+" operator is used only for integer addition. I have a function that needs to increment an integer with each recursive call. The function definition:

let rec lst_act x lst c = ...

The original recursive call within that function:

(lst_act x t curr+1)

This function wasn't working as intended and I truly had no idea why. I decided to change the recursive call to this:

(list_act x t (curr + 1))

and voila, it worked. I don't understand how these statements are different, if the + operator is used only for integer addition in ocaml.

Could someone please explain the difference, and what each of those uses of the "+" operator does? Thanks!

Upvotes: 0

Views: 78

Answers (2)

myrtlecat
myrtlecat

Reputation: 2276

Function application has higher precedence than +, so the first way you wrote it is equivalent to:

((lst_act x t curr) + 1)

Upvotes: 6

kne
kne

Reputation: 1418

The reason is that function application has higher precedence (binds more strongly) than binary operators. Hence your expression

lst_act x t curr+1

is parsed as

(lst_act x t curr) + 1

and not as

lst_act x t (curr+1)

as you seem to have assumed. How that code behaves depends on the rest of your program; I cannot say much about that. In any case it is the same addition operator +, but applied to something different.

Incidentally, the choice of precedence is the same as in everyday formulae:

sin(x) + cos(x)

is parsed as (sin(x)) + (cos(x)) not as (sin(x+cos))(x) or sin((x+cos)(x)) or anything else. Only that in OCaml, the parenthesis are optional in function application, so that it is equivalent to

sin x + cos x

(To prevent nitpicks: In order for the above to typecheck, sin and cos are not the ones from Pervasives which operate on float.)

Upvotes: 3

Related Questions