OCaml 中的函数重载

发布于 2024-11-26 13:59:45 字数 555 浏览 1 评论 0原文

我定义了一些类型:

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

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

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 中的替代方法是什么?我们是否必须以不同的方式命名这两个函数?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟酒忠诚 2024-12-03 13:59:45

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文