Ocaml - Forward Declaration (Classes)

I need to have two classes referencing each other. Is there a way in Okamla to make the First Declaration of one of them?

(I do not think this is possible, as with simpler material with the word and ).

Or maybe it is possible, but in a different way than I tried?

+4
source share
2 answers

Ocaml has nothing like forward declarations (i.e. the promise that something will be defined in the end), but it has recursive definitions (i.e. a block of things that are declared and then immediately defined in terms of each friend). Recursive definitions are possible between expressions, types, classes, and modules (and more); mutually recursive modules allow you to recursively define mixed sets of objects.

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

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

Or you can use parameterized classes . Following the previous example, you:

 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 

Output Interface:

 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 
+2
source

All Articles