1

作为 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) ...
4

1 回答 1

3

在表达式let get_bar_3 (comp : string_or_float_component)中,comp是一个枚举类型:aStr of something或 a 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;;
于 2018-05-06T08:02:08.317 回答