OCaml:类型检查对象
如果我有一个对象,我如何确定它的类型? (OCaml 是否有相当于 Java 的 instanceof
运算符?)
If I have an object, how can I determine its type? (Is there an OCaml equivalent to Java's instanceof
operator?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
OCaml 对对象具有结构类型,而不是像 Java 中的主格类型。所以对象的类型基本上是由它的方法决定的(并且只能决定)。 OCaml 中的对象可以直接创建,无需通过类之类的东西。
您可以编写要求其参数对象具有某些方法(并且这些方法具有某些类型)的函数;例如,以下方法采用的参数是任何具有“bar”方法的对象:
OCaml has structural typing for objects rather than nominative typing as in Java. So the type of an object is basically determined (and only determined) by its methods. Objects in OCaml can be created directly, without going through something like a class.
You can write functions which require that its argument objects have certain methods (and that those methods have certain types); for example, the following method takes an argument that is any object with a method "bar":
“将对象与模式匹配” 上有一个讨论="http://lambda-the-ultimate.org/node/1960" rel="noreferrer">Lambda the Ultimate(本文使用 Scala 作为语言,因此不会回答您的问题)。更相关的Ocaml 邮件列表线程 表示对象没有 RTTI/安全向下转型。
对于代数(非对象)类型,您显然有:
称为 (模式)匹配
有人确实写了 <允许向下/向上的 href="http://www-apr.lip6.fr/~chaillou/Public/Dev/coca-ml/index-en.html" rel="noreferrer">扩展铸造 Ocaml 对象。
There's a discussion of "Matching Objects With Patterns" on Lambda the Ultimate (the paper uses Scala as the language, so won't answer your question). A more relevant Ocaml mailing list thread indicates that there's no RTTI/safe-downcasting for objects.
For algebraic (non object) types you obviously have:
called (pattern) matching
Someone did write an extension that allows down/up-casting Ocaml objects.
简而言之,您必须对自己的 RTTI 机制进行编码。 OCaml 不提供 RTTI 或向上/向下转换(后者部分是因为继承和子类型在 OCaml 中是正交的,而不是像 Java 中那样统一)。
您可以使用字符串或多态变体来对类和对象中的类型信息进行编码。我相信 LablGTK 可以做到这一点,并提供一个实用程序库来支持对象标记和向上/向下转换。
In short, you have to encode your own RTTI mechanism. OCaml provides no RTTI or up/down casting (the latter in part because inheritance and subtyping are orthogonal in OCaml rather than unified as in Java).
You could do something with strings or polymorphic variants to encode type information in your classes and objects. I believe that LablGTK does some of this, and provides a utility library to support object tagging and up/down casting.