开发者

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 = (.开发者_JS百科..)

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜