OCaml中的函数重载

Sof*_*mur 8 ocaml overloading

我已经定义了一些类型:

type box = Box of int
type table = Table of int
type compare_result = Lt | Eq | Gt
Run Code Online (Sandbox Code Playgroud)

似乎在OCaml中,我们不能定义具有相同名称但不同类型的参数的2个函数:

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 *)
Run Code Online (Sandbox Code Playgroud)

那么有谁能告诉我OCaml的替代方案是什么?我们必须以不同的方式命名这两个函数吗?

Pas*_*uoq 6

是的,最简单的解决方案就是以不同方式调用函数.允许执行此操作的程序使类型系统变得非常复杂(而不是专家无法设计解决方案:当他们这样做时,您会发现它无法使用).

用于编写单个函数的现有解决方案compare是OCaml中的对象系统,以及Haskell中的类型类(对相同基本类型系统的不同扩展).但是保持简单的片段并以compare不同的方式命名您的函数要简单得多.

  • 创建compare_box和compare_table的另一种方法是将每个类型和比较函数包装在它们自己的模块中.然后,您将调用Box.compare和Table.compare. (9认同)