OCaml Type Inferencing

Viewed 58

I'm just starting to learn OCaml, and I was confused by how the OCaml compiler determines the input type of arguments in certain situations where the argument could be multiple types. I'm assuming I would need to explicitly state the type in these instances? For example:

let sign x =
    if x > 0 then 1
    else if x < 0 then -1
    else 0

let _ = print_int(sign 1.5)

Throws "Error: This expression has type float but an expression was expected of type int"

But don't the comparison operators work with floats as well? Why does the compiler assume that the argument should be an int instead of saying something like the argument type is ambiguous (unless I'm mistaken and the type actually is not ambiguous)?

1 Answers

The built-in comparison operators in OCaml have the following type signature: 'a -> 'a -> bool. Note that while the argument types are generic ('a), they are both the same. So, when you have a comparison like x < 0, the compiler sees that the type of the second argument is int and then infer that the type of x must be int as well. Changing your comparisons to use floats, e.g. x < 0. will make your code type-check, but then it would no longer work for int inputs.

Related