Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml - Forward Declaration (Classes)

Tags:

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?

like image 637
mechu Avatar asked Jun 16 '11 19:06

mechu


2 Answers

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
like image 75
2 revs Avatar answered Nov 26 '22 09:11

2 revs


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
like image 21
Paolo Donadeo Avatar answered Nov 26 '22 08:11

Paolo Donadeo