Abs function is not working with abs -10

hi
i want to learn ocaml and i started since days. i have this problem. why the function abs -10 is not working
but when write abs (-10) its work.

This is one of the particularities of OCaml lexical convention: the compiler reads abs -10 as (abs) - (10), and not as (abs) (-10). Consequently, it then raises an error due to the fact that abs is a function of type int->int whereas the binary operator - expected an int as its first argument.

If you want to use the unary operator, they are two possibility: either uses parenthesis abs (-10) or the (other) unary minus operator ~-: abs ~-10 .

but how we can know that the compiler will read the function as abs -10 or
(abs) (-10) ?. I mean for other operation also.

It is defined by precedences of operators. The idea is that some operators binds tighter than another, the same as with a + b * c, from the school we know, that it should be read as a + (b * c) because the * operator has a higher precedence than +. The function application operator, that is written just as a juxtaposition in OCaml, i.e., f x, has higher precedence then any infix, i.e., it binds tigher than operators starting with some non-letter symbol, e.g., +,-,*,/,... It , however, has a precedence that is lower than of the prefix operators, e.g., ~,!. So you can write abs ~-10 where ~- is the prefix unary minus operator. (Note that a single - is the binary minus operator, even if you put it close to a number it will not be treated as a part of the number, neither it will be treated as an unary operator).

4 Likes