OCaml:类型检查对象

发布于 2024-08-04 15:40:08 字数 77 浏览 2 评论 0原文

如果我有一个对象,我如何确定它的类型? (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

画中仙 2024-08-11 15:40:08

OCaml 对对象具有结构类型,而不是像 Java 中的主格类型。所以对象的类型基本上是由它的方法决定的(并且只能决定)。 OCaml 中的对象可以直接创建,无需通过类之类的东西。

您可以编写要求其参数对象具有某些方法(并且这些方法具有某些类型)的函数;例如,以下方法采用的参数是任何具有“bar”方法的对象:

let foo x = x#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":

let foo x = x#bar
失而复得 2024-08-11 15:40:08

“将对象与模式匹配” 上有一个讨论="http://lambda-the-ultimate.org/node/1960" rel="noreferrer">Lambda the Ultimate(本文使用 Scala 作为语言,因此不会回答您的问题)。更相关的Ocaml 邮件列表线程 表示对象没有 RTTI/安全向下转型。

对于代数(非对象)类型,您显然有:

match expr with 
  Type1 x -> x
  Type2 (x,y) -> y

称为 (模式)匹配

有人确实写了 <允许向下/向上的 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:

match expr with 
  Type1 x -> x
  Type2 (x,y) -> y

called (pattern) matching

Someone did write an extension that allows down/up-casting Ocaml objects.

微暖i 2024-08-11 15:40:08

简而言之,您必须对自己的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文