I have defined some types:
type box = Box of int
type table = Table of int
type compare_result = Lt | Eq | Gt
It seems that in OCaml, we can't define 2 functions with same name but different types of arguments:
let compare (a: box) (b: box): compare_result = (...)
let compare (a: table) (b: table): compare_result = (...)
let res_box = compare (Box 1) (Box 2) in (* which is supposed to call the first funciton *)
let res_table = compare (Table 1) (Table 2) in (* which is supposed to call the second function *)
So could anyone tell me what is the alternative in OCaml to do this? Do we have to name these 2 functions differently?
They can be used as a function in ocaml. A function call has the form f arg1 arg2 with function named f , while operator such as + is used in the form arg1 + arg2 . Sometimes it is useful to call operators in the function form, so that the power of function and its syntax fully apply to all operators.
OCaml doesn't have a return keyword — the last expression in a function becomes the result of the function automatically.
Yes, the easiest solution is simply to call the functions differently. Allowing programs that do this vastly complicates the type system (not to the point that it isn't possible for experts to design a solution: to the point that you would find it unusable when they do).
Existing solutions for writing a single function compare
are the object system in OCaml, and type classes in Haskell (a different extension to the same base type system). But it's much simpler to stay in the simple fragment and to name your functions compare
differently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With