内置类型上的 OCaml 模式匹配

发布于 2024-09-11 12:14:01 字数 436 浏览 1 评论 0原文

我正在尝试编写一个多态函数,它需要根据参数的类型做一些稍微不同的事情。有什么方法可以使用内置类型对对象的类型进行模式匹配吗?我正在考虑这样的事情:

let to_string v =
    match v with
    | string -> v
    | int -> string_of_int v
    | _ -> ""

但这似乎不是一个有效的 OCaml 程序。

我见过这个问题,但事实并非如此也不能完全回答我的问题。我更喜欢使用标准的内置类型,而不是为此构造新类型(尽管如果这是唯一的方法我可以这样做)。

I'm trying to write a polymorphic function, which needs to do something slightly different depending on the type of the parameter. Is there any way that I can do a pattern match on the type of the object, using the builtin types? I'm thinking of something along these lines:

let to_string v =
    match v with
    | string -> v
    | int -> string_of_int v
    | _ -> ""

but this doesn't seem to be a valid OCaml program.

I have seen this question, but that doesn't quite answer my question either. I would prefer to use the standard,builtin types rather than constructing new types for this (although I can do that if that is the only way).

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

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

发布评论

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

评论(1

铃予 2024-09-18 12:14:01

事实上这个答案完全适用于你。只能匹配一种类型类,且intstringfloat、...的并集定义的类型不存在,并且需要创建(如前面的答案)。 'a 对特定类型进行操作,但不代表所有类型的联合。

您也许可以使用外部 C 函数执行您想要的操作 (18.3 ),不过,浏览一下原子标签部分,我不确定您是否能够区分 charint

Actually that answer completely applies to you. You can only match one type class, and the type defined by the union of int, string, float, ... does not exist, and needs to be created (as in the previous answer). 'a operates on a particular type, but does not represent a union of all types.

You might be able to do what you want using an external C function (18.3), although, glancing at the atomic tags section, I'm not sure you'll be able to differentiate char and int.

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