Re: Objects as sums

From: Anton Moscal (msk@post.tepkom.ru)
Date: Sat Nov 28 1998 - 11:46:12 MET


Date: Sat, 28 Nov 1998 13:46:12 +0300 (MSK)
From: Anton Moscal <msk@post.tepkom.ru>
To: Didier.Remy@inria.fr
Subject: Re: Objects as sums
In-Reply-To: <19981126165842.07547@morgon.inria.fr>

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



This archive was generated by hypermail 2b29 : Sun Jan 02 2000 - 11:58:17 MET