What does this function do?.

Alain Frisch

A little teaser for OCaml gurus: what does the function below do?

let memoize_obj o =
  let o = Oo.copy o in
  let meths = Obj.dup (Obj.field (Obj.repr o) 0) in
  Obj.set_field (Obj.repr o) 0 meths;
  let nmeths : int = Obj.magic (Obj.field meths 0) in
  for i = 0 to nmeths - 1 do
    let idx = i * 2 + 2 in
    let old_f = Obj.field meths idx in
    let memo = lazy (Obj.magic old_f o) in
    let new_f _self = (*assert(_self == Obj.repr o);*) Lazy.force memo in
    Obj.set_field meths idx (Obj.repr new_f);
  done;
  o

In a forthcoming post, I’ll describe how this function will help us shrink our code base. In the meantime, I hope someone will comment and explain what the function does!