Ocaml - 前向声明(类)

发布于 2024-11-15 23:13:12 字数 127 浏览 0 评论 0原文

我需要有两个相互引用的类。 Ocaml 有什么办法可以对其中之一进行前向声明吗?

(我认为这是不可能的,因为使用单词 更容易)。

或者也许这是可能的,但与我尝试的方式不同?

I need to have two classes refering to each other. Is there any way in Ocaml to make Forward Declaration of one of them?

(I don't think it's possible as with easier stuff with word and).

Or maybe it is possible, but different way than how i tried?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

娇妻 2024-11-22 23:13:12

Ocaml 没有诸如前向声明之类的东西(即最终将定义某些内容的承诺),但它具有递归定义(即声明然后立即相互定义的事物块)。表达式、类型、类和模块(等等)之间可以进行递归定义;相互递归模块允许递归地定义混合对象集。

您可以使用带有关键字 and 的递归定义来解决您的问题:

class foo(x : bar) = object
  method f () = x#h ()
  method g () = 0
end

and bar(x : foo) = object
  method h () = x#g()
end

Ocaml doesn't have anything like forward declarations (i.e. a promise that something will be defined eventually), but it has recursive definitions (i.e. a block of things that are declared and then immediately defined in terms of each other). Recursive definitions are possible between expressions, types, classes, and modules (and more); mutually recursive modules allow mixed sets of objects to be defined recursively.

You can solve your problem using a recursive definition with the keyword and:

class foo(x : bar) = object
  method f () = x#h ()
  method g () = 0
end

and bar(x : foo) = object
  method h () = x#g()
end
躲猫猫 2024-11-22 23:13:12

或者您可以使用参数化类。按照前面的示例,您将得到:

class ['bar] foo (x : 'bar) =
object
    method f () = x#h ()
    method g () = 0
end

class ['foo] bar (x : 'foo) =
object
    method h () = x#g()
end

推断的接口是:

class ['a] foo : 'a ->
    object
        constraint 'a = < h : unit -> 'b; .. >
        method f : unit -> 'b
        method g : unit -> int
    end
class ['a] bar : 'a ->
    object
        constraint 'a = < g : unit -> 'b; .. >
        method h : unit -> 'b
    end

Or you could use parameterized classes. Following the previous example you have:

class ['bar] foo (x : 'bar) =
object
    method f () = x#h ()
    method g () = 0
end

class ['foo] bar (x : 'foo) =
object
    method h () = x#g()
end

The inferred interface is:

class ['a] foo : 'a ->
    object
        constraint 'a = < h : unit -> 'b; .. >
        method f : unit -> 'b
        method g : unit -> int
    end
class ['a] bar : 'a ->
    object
        constraint 'a = < g : unit -> 'b; .. >
        method h : unit -> 'b
    end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文