From mboxrd@z Thu Jan 1 00:00:00 1970 Received: (from majordomo@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id TAA10142; Sat, 21 Sep 2002 19:30:41 +0200 (MET DST) X-Authentication-Warning: pauillac.inria.fr: majordomo set sender to owner-caml-list@pauillac.inria.fr using -f Received: from concorde.inria.fr (concorde.inria.fr [192.93.2.39]) by pauillac.inria.fr (8.7.6/8.7.3) with ESMTP id TAA10316 for ; Sat, 21 Sep 2002 19:30:40 +0200 (MET DST) Received: from lobus.fungible.com (adsl-64-161-114-6.dsl.snfc21.pacbell.net [64.161.114.6]) by concorde.inria.fr (8.11.1/8.11.1) with ESMTP id g8LHUc528792 for ; Sat, 21 Sep 2002 19:30:39 +0200 (MET DST) Received: by lobus.fungible.com (Postfix, from userid 1000) id 00D507F5B; Sat, 21 Sep 2002 10:30:35 -0700 (PDT) Date: Sat, 21 Sep 2002 08:09:44 -0700 From-Tims-Fingers: true To: caml-list@inria.fr Subject: [Caml-list] How to downcast in OCAML Message-Id: <20020921173035.00D507F5B@lobus.fungible.com> From: tim@fungible.com (Tim Freeman) Sender: owner-caml-list@pauillac.inria.fr Precedence: bulk For what it's worth (which may not be much), it is possible to write classes in OCAML that are downcastable. Here's how. -- Tim Freeman tim@fungible.com GPG public key fingerprint ECDF 46F8 3B80 BB9E 575D 7180 76DF FE00 34B1 5C78 module type Foo = sig class type superclass = object method data: exn end class subclass_1: string -> object inherit superclass method s: string end exception Subclass_1 of subclass_1 class subclass_2: int -> object inherit superclass method i: int end exception Subclass_2 of subclass_2 val x: superclass end module Foo: Foo = struct class type superclass = object method data: exn (* You can put more methods here if you like. *) end class subclass_1_impl (s: string) (makeexn: subclass_1_impl -> exn) = object (self: 'self) constraint 'self = #superclass method data: exn = makeexn (self :> subclass_1_impl) method s: string = s end exception Subclass_1 of subclass_1_impl class subclass_1 (s: string) = subclass_1_impl s (fun sc -> Subclass_1 sc) class subclass_2_impl (i: int) (makeexn: subclass_2_impl -> exn) = object (self: 'self) constraint 'self = #superclass method data: exn = makeexn (self :> subclass_2_impl) method i: int = i end exception Subclass_2 of subclass_2_impl class subclass_2 (i: int) = subclass_2_impl i (fun sc -> Subclass_2 sc) let _ = Random.self_init () let x: superclass = if Random.bits () mod 2 = 0 then (new subclass_1 "blort" :> superclass) else (new subclass_2 17 :> superclass) let _ = match x#data with Subclass_1 s1 -> Format.printf "s is %s.\n@?" s1#s | Subclass_2 s2 -> Format.printf "i is %d.\n@?" s2#i | _ -> failwith "Downcast failed" end ------------------- To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/ Beginner's list: http://groups.yahoo.com/group/ocaml_beginners