OCaml has distinct syntax for BOTH:
- float operations vs. int operations. Float operations end in dot:
+.. - float literals vs. int literals. Floats literals end in dot:
3..
# 3 + 3;;
- : int = 6
# 3. +. 3.;;
- : float = 6.
# 3. + 3;;
Error: This expression has type float but an expression was expected of type
int
I can see using one of these mechanisms to disambiguate, but why are two needed always?
For example, I could see a case where . is sometimes needed at the end of a literal, but not why it is needed for 3 +. 3 where OCaml could figure out that we want float arithmetic because we're saying we want float arithmetic.
I'm looking for specific technical justification based on interaction with other language features–not opinion or arguments from ergonomics.
Each function has a type, this is what lead the OCaml syntax. If you pass an argument which is not appropriate, the compiler reject your code with an error.
This seems pretty obvious, but this is also the case in any function, including the basic math operators: the function named
+.has the type :That's all. If you give an int instead of a float, the compiler tells you your code is wrong. OCaml does not figure anything. The compiler just check if the parameters are valid with the function signature. They aren't ? Error.
You could argue that the point is false, because any C compiler will accept your line of code and produce a float as result as expected. But this is another language, and even if this could¹ work, this is not allowed inside OCaml. You can't escape the type.
The language specification is pretty clear : each function is defined by the type of the parameters, and you can't give a multityped parameter.
This allow the compiler to optimize the code easilly , but you have to explicitally convert the argument into the one expected by your function signature.
¹ It will not actually, because the memory representation for an
intin OCaml is not exactly the same as theintin C (but this is another subjet)