Prototype based OCaml

Talking about prototypes, here is a little module which allows prototype based programming in OCaml. I'll warn you right now : it's horrible, but funny.

type obj =
    Empty
  | Obj of (string, string) Hashtbl.t * obj

let create ?(proto=Empty) () = Obj (Hashtbl.create 111, proto)

let set o k v =
  match o with
    Empty -> raise Not_found
  | Obj (o, p) -> Hashtbl.replace o k (Obj.magic v)

let rec get o k =
  match o with
    Empty -> raise Not_found
  | Obj (o, p) ->
      try
        Obj.magic (Hashtbl.find o k)
      with Not_found -> get p k

There is nothing difficult to understand (it was actually difficult to do). An object is just a hashtable and a parent object. Typing is bypassed using Obj.magic

Let's have a little fun:

open Proto

let _ =
  let p = create () in
  set p "foo" "p.foo";
  set p "baz" "p.baz";

  let o = create ~proto:p () in
  set o "foo" "o.foo";
  set o "bar" (fun f -> f (get o "baz"));

  print_endline (get p "foo");
  print_endline (get p "baz");
  print_endline (get o "foo");
  ((get o "bar") : 'a->'b) print_endline;

The result:

$ ./prototest
p.foo
p.baz
o.foo
p.baz

Note : This is only a proof of concept, never use this in OCaml, it is not at all compliant with OCaml philosophy. It's funny, however :D

Leave a Reply