Function Overloading in OCaml

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 cannot define 2 functions with the same name but with 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 can anyone tell me what is the alternative in OCaml for this? Should we call these 2 functions in different ways?

+6
source share
1 answer

Yes, the easiest solution is to simply call the functions in different ways. Providing the programs that do this greatly complicates the type system (not so that the experts are not able to develop a solution: to the point that you cannot use it when they do).

The existing solutions for writing one compare function are the object system in OCaml and class types in Haskell (another extension to the same system of the base type). But it’s much easier to stop in a simple snippet and name your compare functions differently.

+6
source

Source: https://habr.com/ru/post/893782/


All Articles