内置类型上的 OCaml 模式匹配
我正在尝试编写一个多态函数,它需要根据参数的类型做一些稍微不同的事情。有什么方法可以使用内置类型对对象的类型进行模式匹配吗?我正在考虑这样的事情:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实上这个答案完全适用于你。只能匹配一种类型类,且
int
、string
、float
、...的并集定义的类型不存在,并且需要创建(如前面的答案)。'a
对特定类型进行操作,但不代表所有类型的联合。您也许可以使用外部 C 函数执行您想要的操作 (18.3 ),不过,浏览一下原子标签部分,我不确定您是否能够区分
char
和int
。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
andint
.