作为 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 不能在 get_bar_3 中推断出组件是 Str | 飞度。
也许这种把戏是可能的?
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) ...