Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 265
SoftTimur Avatar asked Jul 28 '11 14:07

SoftTimur


People also ask

How do you use functions in OCaml?

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.

How do I return a value in OCaml?

OCaml doesn't have a return keyword — the last expression in a function becomes the result of the function automatically.


1 Answers

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.

like image 60
Pascal Cuoq Avatar answered Sep 21 '22 10:09

Pascal Cuoq