Version française
Home     About     Download     Resources     Contact us    
Browse thread
Local opening of modules
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Anton Moscal <msk@p...>
Subject: Re: Objects as sums
On Thu, 26 Nov 1998, Didier Remy wrote:

> class a = object (self : 'a)
>   method b () = ((assert false): 'a)
>   method c () = ((assert false): 'a)
> end;;
> 
> Here, the methods b and c return an object of the same type as their own
> type. In particular, in a subclass, they will return an object of the type
> of objects of the subclass...
> 
> Then, the rest of the example works unchanged.
> 
>     class c = object (self)
>       inherit a
>       method c () = self
>     end;;

This is not solution of my task. I want to simulate by ocaml classes the
following C++ program:

# include <stdlib.h>

enum {NODE, LEAF};
class Node;
class Leaf;
class Tree { public:
  virtual int tag () = 0;
  virtual Node * node () { abort (); return 0; }
  virtual Leaf * leaf () { abort (); return 0; }
};

class Leaf: public Tree { public:
  int val;
  int tag () { return LEAF; }
  Leaf * leaf () { return this; }
};

class Node: public Tree { public:
  Tree * l, * r;
  int tag () { return NODE; }
  Node * node () { return this; }
};

int sum (Tree * tree)
{
  switch (tree -> tag ()) 
    {
    case LEAF: return tree -> leaf () -> val;
    case NODE: return sum (tree -> node () -> l) + sum (tree -> node () -> r);
    }
}

This program may be easily translated to ocaml as follows:

type tree = Leaf of int | Tree of tree * tree
let rec sum = function
    Leaf v -> v
  | Tree (l, r) -> sum l + sum r

but I would like to have solution with classes.

Your proposals do not work: type of (tree#node ()) will have `tree' type
and will fail on selection of a method, specific for node.

PS: this trick implements type-safe conversion down to objects hierarchy.
    Question of my interest is the following: whether such
    conversion is possible or not?

Regards, 
Anton