Polymorphic recursive classes

Is there a way to make a polymorphic recursive class?

Here’s a simple example that does not compile:

class ['a] listy x =
    method list = x
    method more_lists : unit -> 'a list listy =
      fun () -> new listy [x]

It gives the error message

Error: The abbreviation listy is used with parameters 'a list listy
       which are incompatible with constraints 'a listy

I can fall back on the record of function pointers approach, but I’m finding the class syntax a lot nicer to use, so I thought I’d ask – especially since for advanced type things, it can sometimes be hard to tell the difference between impossible and just missing the right magical incantation.


You are hitting a regularity restriction of OCaml’s classes. Basically it means that class should be used in itself with the same type parameters that it has in it’s definition. There is the same concept for algebraic data types.

An old Caml-list thread may be helpful for this topic. I don’t have exact link, but you should look for a thread started on Oct 19, 2015 by Spiros Eliopoulos, it has a topic "map"-ing parameterized class types. I’m not sure that I’m able to forward these messages to Discus…

1 Like

Never forget about https://inbox.ocaml.org mailing list archive software that actually works.

Here’s the thread.


Thanks! I guess I’ll stick with a record of function pointers then.