Ocaml:在参数类型中使用记录和变量
作为Ocaml的新手,我正在使用类型并试图了解变体是如何工作的 以下是示例:Ocaml:在参数类型中使用记录和变量,ocaml,record,variant,bucklescript,Ocaml,Record,Variant,Bucklescript,作为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_
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|Flt
也许这种把戏在某种程度上是可能的
type 'a string_or_float =
| Str of string 'a
| Flt of float 'a
谢谢
(我正在使用bucklescript)
编辑:
意识到我的问题更多地与设计有关。我可以这样做:
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) ...
在表达式
中,让get\u bar\u 3(comp:string\u或\u float\u component)
,comp
是一种枚举类型:某事物的Str
或某事物的Flo
。
在任何情况下,comp
此时不是记录类型,只有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;;
我认为您已经在函数中添加了模式匹配,我想OCaml设计人员更关心的是开发速度更快、更实用的案例编译器,而不是最聪明的编译器。但是可能是严格类型编程的一些教条(Str和Flt是单子还是smth)可能是关于显式多态性注释的一章可以为您澄清吗?谢谢你,塞奇,我去查一下!谢谢你!我想知道,既然变量可以包含所有内容,它就不能保证它的所有构造函数都共享同一个结构。第4.2节揭示了我遇到的问题。让我们看看这个魔法是如何运作的!