【发布时间】:2018-05-06 06:53:58
【问题描述】:
作为 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) ...
【问题讨论】:
-
我认为你已经在你的函数中添加了模式匹配,我猜 OCaml 设计师更关心开发更快更实用的编译器,而不是最聪明的编译器。但可能是一些严格类型编程的教条(是 Str 和 Flt 类型的 monad 或 smth)
-
可能是关于显式多态性注释的章节,可以为您澄清吗? caml.inria.fr/pub/docs/manual-ocaml/polymorphism.html
-
谢谢 Serge,我会检查一下!
标签: ocaml record variant bucklescript