Browse thread
[Caml-list] How to downcast in OCAML
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | tim@f... |
| Subject: | [Caml-list] How to downcast in OCAML |
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