在阅读Real World OCaml的书时,我遇到了以下类型声明(第6章:变体):
# type color =
| Basic of basic_color * weight (* basic colors, regular and bold *)
| RGB of int * int * int (* 6x6x6 color cube *)
| Gray of int (* 24 grayscale levels *)
;;
type color =
Basic of basic_color * weight
| RGB of int * int * int
| Gray of int
我认为可以进一步限制RGB和Gray变体。例如,RGB元组中的每个int只能具有值0-5。
在Erlang中,我会这样做:
-type rgbint() :: 0 | 1 | 2 | 3 | 4 | 5.
-type rgb() :: {rgb_int(), rgb_int(), rgb_int().
但是,当我在OCaml(在utop中)尝试此操作时,它抱怨:
# type rgbint = 0 | 1 | 2 | 3 | 4 | 5 ;;
Error: Parse error: [type_kind] expected after "=" (in [opt_eq_pluseq_ctyp])
问题:
衷心的祝福
伊万
通过某种基本类型的值列表定义类型是有意义的,但是OCaml没有这样的类型。它具有一组像int
和的原始类型char
。您可以定义自己的新基本类型,其值是诸如Yes
和的文字No
。(当定义这样的文字时,它看起来像是大写的标识符。)您可以将它们与参数化类型(如列表,数组等)结合使用。
如果您确实希望将int值限制在某个范围内,则可以将其定义为模块接口隐藏的抽象类型。在模块中,您需要定义要在有限的整数范围内支持的所有操作。(请注意,此类类型不会在常规算术运算中关闭。)
您还可以定义:
type rgbint = RBG0 | RGB1 | RGB2 | RGB3 | RGB4 | RGB5
在实践中,这可能最终会做,尽管当您将基础值视为数字时,这种类型会很麻烦。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句