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] difficulties narrowing OO types
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2001-11-15 (06:44)
From: Jacques Garrigue <garrigue@k...>
Subject: Re: [Caml-list] difficulties narrowing OO types
From: Jacques Garrigue <>

> Since the problem is with inheritance, and not with subtyping, there
> are workarounds to define such classes. Basically the idea is to keep
> the type of self as a parameter to the class.

Actually, I realized after posting my previous message that it was a
bit far-fetched for simple cases. If you just want to be able to list
objects which have the type of the current class, then recursion on
the type of self is enough and simpler.

Here is the same example as before:

class base ~pos ~friends =
  object (_ : 'a)
    method pos : int = pos
    method friends : 'a list = friends

class extended ~pos ~friends ~name =
    inherit base ~pos ~friends
    method name : string = name

Which give types:
class base :
  pos:int ->
  friends:('a list as 'b) ->
  object ('a) method friends : 'b method pos : int end
class extended :
  pos:int ->
  friends:('a list as 'b) ->
  name:string ->
  object ('a) method friends : 'b method name : string method pos : int end

And you can even coerce with semi-explicit coercions:
# let e = new extended ~pos:1 ~friends:[] ~name:"e";;
val e : extended = <obj>
# let b = new base ~pos:2 ~friends:[(e :> base)];;
val b : base = <obj>

Hope this helps.

Jacques Garrigue
Bug reports:  FAQ:
To unsubscribe, mail  Archives: