Mutually Recursive Types

Unlike C/C++, Ocaml does not allow you to have “forward declarations” of types. In other words, if you have a record type A that has an entry that of type B and type B has an entry of type A, you cannot forward declare B so that it is in scope for record type A. In code:

type A = { foo : B }

type B = Bar of A

To get around this limitation, Ocaml has “mutually recursive types” with the keyword “and”. Now, “and” is overloaded to work with mutually recursive functions as well. So, if you want to do this you can use “and” thusly:

type A = { foo : B }
and
B = Bar of A

There is one thing to notice here: B does not have a “type” keyword in front of it. This isn’t necessary because the idea of “type” crosses the “and” boundary. Sometimes, you get long chains of this which can look slightly odd but isn’t too much of a problem most times.

Leave a comment

About cyocum

user-pic Celticist, Computer Scientist, Nerd, sometimes a poet…