Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] Recursive type and class
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-08-31 (03:25)
From: John Max Skaller <skaller@o...>
Subject: Re: [Caml-list] Recursive type and class
David Frese wrote:

> Hello folks,
> I have a problem with mixing a class and a type recursively. Written
> down directly, I want to have something like this:
> type atype = Obj of aclass | I of int
> class aclass = object
>   val mutable field0 : atype = I 5
> end
> But this does not work, of course. Can anyone tell me, how this can be
> done?

You first declare a class *type* with a type parameter:

class type ['t] aclass_t' = object val mutable field0: 't end

Now you declare the recursion:

type atype = Obj of atype aclass_t' | I of int

and finally you make a typedef for the class:

type aclass_t = atype aclass

Well that's got the typing right, so now you can
provide an implementation:

class ['t] aclass init = object val mutable field0: atype = init end

Note that the init value had to be lifted out, so you need a monomorphic

function to instantiate the instance class:

let mkclass () = new aclass (I 5)

Finally, to check it works:

# Obj (mkclass ());;
- : atype = Obj <obj>

[You might be able to make this simpler using a constraint,
I've never quite figured them out :]

John Max Skaller,
snail:10/1 Toxteth Rd, Glebe, NSW 2037, Australia.

To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: