Version française
Home     About     Download     Resources     Contact us    
Browse thread
Why can't I call a function over a subclass?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jacques Garrigue <garrigue@m...>
Subject: Re: [Caml-list] Re: Why can't I call a function over a subclass?
From: "Luca de Alfaro" <luca@dealfaro.org>

> Yes, here is some code.  Any help would be very much appreciated.
> The following fails to type check:
> 
> class p (x: int) = object
>   method plus1 : int = x + 1
> end
> 
> class p2 (x: int) = object
>   inherit p x
>   method plus2 : int = x + 2
> end
> 
> class r = object (self)
>   val mutable l = []
>   method make_el x = new p x
>   method add (x: int) : unit = l <- (self#make_el x) :: l
>   method length : int = List.length l
>   method total : int = List.fold_left (fun t el -> t + el#plus1) 0 l
> end
> 
> class r2 = object
>   inherit r
>   method make_el x = new p2 x
>   method total2 : int = List.fold_left (fun t el -> t + el#plus2) 0 l
> end

Zheng Li already provided an answer to your problem. However Zheng's
answer, while doing exactly what you were trying to do, use virtual
value fields, which are a new feature in 3.10.
A more standard way to do this would be to use a private virtual
method, as make_el is the same across all instances of a specific
class.

class virtual r = object (self)
  val mutable l = []
  method private virtual make_el : int -> #p
  method add x = l <- self#make_el x ::l
  method length = List.length l
  method total = List.fold_left (fun t el -> t + el#plus1) 0 l
end
class r1 = object inherit r method make_el = new p end
class r2 = object inherit r 
  method make_el = new p2 
  method total2 = List.fold_left (fun t el -> t + el#plus2) 0 l
end

Practically, these two solutions are equivalent.

Jacques Garrigue