2011-07-28 65 views
6
超载

我已经定义了一些类型:功能OCaml中

type box = Box of int 
type table = Table of int 
type compare_result = Lt | Eq | Gt 

看来,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 *) 

所以任何人都可以告诉我在OCaml中做什么替代方法?我们必须以不同的方式命名这两个功能吗?

+1

请注意,您的第二个'compare'声明将隐藏前一个(在Ocaml中没有函数重载)。 – akoprowski

回答

6

是的,最简单的解决方案是简单地调用不同的功能。允许这样做的程序极大地增加了类型系统的复杂性(而不是专家设计解决方案的可能性不大),以至于当他们这样做时,你会发现它不可用。

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

+8

创建compare_box和compare_table的另一种方法是将每个类型和比较函数包装在它们自己的模块中。然后您可以调用Box.compare和Table.compare。 – hcarty

+0

如果您计划从类型创建“Set”或“Map”,创建单独的模块也很方便。 – nlucaroni