在 OCaml 中扩展现有类型 [英] Extending an existing type in OCaml

查看:27
本文介绍了在 OCaml 中扩展现有类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在做一些 OCaml 编程来学习这门语言并更熟悉函数式编程.最近,我开始认为我希望能够扩展现有类型(内置类型或我自己的类型),例如:

I've been doing some OCaml programming lately to learn the language and to get more acquainted with functional programming. Recently, I've started to think that I'd like to be able to extend an existing type (either built in-or one of my own), for example:

type bexp =
  And of bexp * bexp
| Or of bexp * bexp
| Xor of bexp * bexp
| Not of bexp;;

现在假设我想向这种类型添加一个 Nop 变体,但仅用于新类型 - 有点像继承.嘿,这些应该是代数数据类型,对吧?那么为什么不喜欢这样的:

Now let's say I want to add a Nop variant to this type, but only for use in a new type - kind of like inheritance. Hey, these are supposed to be Algebraic data types, right? So why not something like:

type nbexp = bexp | Nop nbexp ;;

...但这不是有效的 OCaml,它给出了一个语法错误.基本上,我想做的是说我希望 nbexp 包含 bexp 包含的所有内容,并为此添加一个 Nop.我想这是不可能的,因为,例如,如果您使用 And 构造函数,则无法确定它是 bexp 类型还是 nbexp 类型.(我认为采用 nbexp 的构造函数 Nop 也可能有问题.)

...but this isn't valid OCaml, it gives a syntax error. Basically, what I'm trying to do is say that I want nbexp to include everything bexp includes and also add a Nop to that. I suppose this isn't possible because, if for example you used the And constructor there would be no way to determine if it was a bexp type or a nbexp type. ( I think the constructor Nop taking a nbexp may also be problematic.)

那么有没有办法在 OCaml 中做这样的事情?而且,这是在 Haskell 中可行的事情吗(也许是类型类)?

So is there any way to do something like this in OCaml? And, is this the sort of thing that's doable in Haskell (with typeclasses, perhaps)?

推荐答案

一个有趣的解决方案是使用多态变体:

An interesting solution is to use polymorphic variant:

type bexp =
[ `And of bexp * bexp
| `Or of bexp * bexp
| `Xor of bexp * bexp
| `Not of bexp ];;

type nbexp = [ bexp | `Nop of nbexp ];;

请注意,多态变体比普通变体更棘手,但允许类型扩展.

Note that polymorphic variants are trickier than normal ones, but allow extension of type.

一个有趣的表达式评估示例,带有扩展,使用多态变体可以在 ocaml 源的测试目录中找到,参见 svn

An interesting example of expression evaluation, with extension, using polymorphic variant can be found in a test directories of the ocaml source, see the svn

这篇关于在 OCaml 中扩展现有类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆