作为Ocaml的新手,我正在玩类型并尝试了解变体的工作原理。
这是示例:
type 'a component =
{ foo : int;
bar : 'a }
type string_or_float_component =
| Str of string component
| Flt of float component
let get_foo_1 (comp: 'a component) = comp.foo
(* works *)
let get_foo_2 (Str comp) = comp.foo
(* works *)
let get_bar_3 (comp : string_or_float_component) = comp.foo
(* This expression has type string_or_float_component
but an expression was expected of type 'a component *)
我不是试图找到最佳解决方案(如模式匹配(,只是理解为什么 ocaml 无法推断出该组件是 Str | Flt get_bar_3。
也许这种把戏是可能的?
type 'a string_or_float =
| Str of string 'a
| Flt of float 'a
谢谢
(我正在使用扣子脚本(
编辑:
意识到我的问题更多地与设计有关。我可以使用这样的东西:
type string_or_float =
| Str of string
| Flt of float
type 'a component = { foo: int; bar: 'a }
let get_bar_3 (comp : string_or_float component) ...
在表达式let get_bar_3 (comp : string_or_float_component)
中,comp
是一个枚举类型:一个Str of something
或一个Flo of something
。 无论如何,此时comp
不是记录类型,只有something
是记录类型。
要从something
中提取字段:
let get_bar_3 (comp : string_or_float_component) = let Str a = comp in a.foo;;
这将在编译类型时给出警告。 完整的代码是这样的:
let get_bar_3 (comp : string_or_float_component) = match comp with
| Str a -> a.foo
| Flt a -> a.foo;;