Ocaml在另一个类型声明中选择类型的子类型 [英] Ocaml selecting a type's subtype in another type declaration
问题描述
给出两个类型声明,我想在另一个类型声明中使用一个类型声明的子类型.例如,假设我有红色,蓝色,黄色的颜色,那么在制作另一种类型时如何具体引用每个子类型?此示例并非专门针对我的问题,而是对我所面临问题的简化.我已经尝试了下面的示例,直接引用了Red等.我还尝试了红色的颜色,即:
Given two type declarations, I want to use a subtype of one type declaration in another. For instance, say I have colours of Red, Blue, Yellow, how would I specifically reference each subtype when making another type? This example isn't specific to my problem, but it's a simplification of the problem I'm facing. I've tried the below example, straight up referencing Red, etc. I've also tried Red of colour i.e:
type colour =
| Red
| Blue
| Yellow
type shape =
| Rectangle * Red
| Square * Yellow
关于上面的说明,我试图将矩形的颜色类型设置为红色,将正方形的颜色类型设置为黄色,
Notice above how I'm trying to force a colour type of Red for the rectangle and a colour type of Yellow for the square, how would I go about doing this?
推荐答案
如果您真的想将Rectangle
和Square
限制为仅一种颜色,则无需表示颜色-这将是多余的.但我认为您要问的是比这更笼统的问题.
If you really wanted to limit Rectangle
and Square
to just one color, you wouldn't need to represent the color--it would be redundant. But I assume you're asking a more general question than this.
OCaml不支持这种类型的变体的子类型化.您不能创建仅使用Red
作为其可能值的新类型,或者仅使用Red
和Yellow
作为其新类型.
OCaml doesn't support subtyping for this type of variant. You can't make a new type that just has Red
as its possible values, or just Red
and Yellow
.
但是,所谓的多态变体"支持子类型化.你可以有这样的东西:
However, subtyping is supported for so-called "polymorphic variants". You can have something like this:
# type rby = [ `Red | `Blue | `Yellow ];;
type rby = [ `Blue | `Red | `Yellow ]
# type r = [ `Red ];;
type r = [ `Red ]
# type y = [`Yellow ];;
type y = [ `Yellow ]
# type shape = Rectangle of r | Square of y;;
type shape = Rectangle of r | Square of y
# Rectangle `Yellow;;
Error: This expression has type [> `Yellow ]
but an expression was expected of type r
The second variant type does not allow tag(s) `Yellow
# Rectangle `Red;;
- : shape = Rectangle `Red
请注意,OCaml不会自动推断子类型关系.您需要使用:>
标记明确要求它们.
Note that OCaml doesn't automatically infer subtyping relations. You will need to ask for them explicitly using the :>
notation.
根据我的经验,多态变体为您的代码增加了很多复杂性.因此,我建议仅当它们确实以其他方式使事情变得更好时才使用它们.
In my experience, polymorphic variants add a lot of complexity to your code. So I would suggest using them only if they really make things better in other ways.
(我还要补充一点,您的类型colour
与C或Java中的枚举或多或少完全相同.因此,您所要查询的内容并不清楚.在C或Java中都无法创建一种新的类型,该类型只有一个枚举中的几个选定值.)
(I would also add that your type colour
is more or less exactly the same as an enum in C or Java. So it's not completely clear what you're asking. There's no way in C or Java either to create a new type that has just a few selected values from an enum.)
这篇关于Ocaml在另一个类型声明中选择类型的子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!