根据真实世界OCaml第11章,行多态不能用于创建异构容器。
特别是,不能使用行多态性将不同类型的对象放置在同一个容器中。例如,不能使用行多态性创建异构元素列表。
举的例子如下:
type square = < area : float; width : int >;;
type shape = < variant : repr; area : float>
and circle = < variant : repr; area : float; radius : int >
and line = < variant : repr; area : float; length : int >
and repr =
| Circle of circle
| Line of line;;
# let hlist: < area: float; ..> list = [square 10; circle 30] ;;
Characters 49-58:
Error: This expression has type < area : float; radius : int >
but an expression was expected of type < area : float; width : int >
The second object type has no method radius正如错误消息如此清楚地说明的那样,元素的类型不匹配。我的问题是为什么行多态不能“隐藏”不匹配的记录的方法(即在容器中的所有类型上做一个交集)?
如果您遵循这一思路--逻辑结论--那么您最终将得到一个类型错误较少的系统,但许多推断类型<>都没有方法。
发布于 2017-01-20 10:03:12
这是可以做到的,但您必须明确地这样做:
let hlist = [(square 10 :> shape); (circle 30 :> shape)]它没有自动完成的原因可能是,否则类型系统将变得不可分辨(根据http://caml.inria.fr/pub/docs/manual-ocaml/objectexamples.html,它已经处于无法判定的边缘)。但我不知道细节。
https://stackoverflow.com/questions/41757151
复制相似问题