Version française
Home     About     Download     Resources     Contact us    
Browse thread
Why can't immediate objects be extended?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Peng Zang <peng.zang@g...>
Subject: Re: [Caml-list] Why can't immediate objects be extended?
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Saturday 12 July 2008 10:12:00 am Richard Jones wrote:
> I'm wondering if there's a reason why one cannot inherit from
> immediate objects? (See description at:
> http://caml.inria.fr/pub/docs/manual-ocaml/manual005.html#ss:immediate-obje
>cts) Is it just a syntax problem because the 'inherit' keyword currently
> needs to take a class type, or is there a deeper reason?

I have no idea, however, using some black magic we can accomplish exactly 
this:

- ----------- snip of temp.ml -------------
(** ported from hash.c **)
let caml_hash_variant name = 
  let acc = ref 0 in
  let len = String.length name in
    for i = 0 to len - 1 do
      acc := (223 * !acc + Char.code (String.get name i)) land 0x7FFFFFFF;
    done;
    !acc
;;

(** the return type is needs casting **)
let addmethod obj methodname methodfun = 
  let methodsuite = Obj.field obj 0 in
  let newms = 
    let nummethods : int = Obj.magic (Obj.field methodsuite 0) in
    let size = Obj.size methodsuite in
    let arr = Array.create (size+2) 0 in
      arr.(0) <- nummethods + 1;
      for i = 1 to size - 1 do
        arr.(i) <- Obj.magic (Obj.field methodsuite i);
      done;
      arr.(size) <- methodfun;
      arr.(size+1) <- caml_hash_variant methodname;
      arr in
  let obj' = Obj.dup obj in
    Obj.set_field obj' 0 (Obj.magic newms);
    obj'
;;
let addmethod = Obj.magic addmethod
let addmethod : (< .. > as 'a) -> string -> ('a -> 'b) -> < .. > = addmethod;;

    

let foo = object method foo = "foo" end;;
let foobar : <foo:string; bar:string> = addmethod foo "bar" (fun _ -> "bar");;

foo#foo;;
foobar#foo;;
foobar#bar;;
- ----------- end snip ----------


        Objective Caml version 3.09.3
# #use "temp.ml";;
val caml_hash_variant : string -> int = <fun>
val addmethod : Obj.t -> string -> int -> Obj.t = <fun>
val addmethod : 'a = <poly>
val addmethod : (< .. > as 'a) -> string -> ('a -> 'b) -> < .. > = <fun>
val foo : < foo : string > = <obj>
val foobar : < bar : string; foo : string > = <obj>
- - : string = "foo"
- - : string = "foo"
- - : string = "bar"
# 


Not pretty, but it works,


Peng
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.7 (GNU/Linux)

iD8DBQFIerBLfIRcEFL/JewRAnTpAJ9LdD09DsVvgJHemCf3ROzGqH+dQwCfRAoX
7sOvInXyvq8jDfF+ucZhzic=
=V3Ki
-----END PGP SIGNATURE-----