caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* [Caml-list] How to mutate immutable record fields?
@ 2011-10-15  8:10 Martin Jambon
  2011-10-15  9:07 ` Nicolas Pouillard
                   ` (2 more replies)
  0 siblings, 3 replies; 5+ messages in thread
From: Martin Jambon @ 2011-10-15  8:10 UTC (permalink / raw)
  To: OCaml Mailing List

Dear fellow OCamlers,


Hints on how to solve this, using any means necessary, will be greatly
appreciated.


Purpose: deserializing a record efficiently, i.e. creating a record
whose field values are available one after another in an unpredictable
order.

Problem: Obj.set_field does the job in most cases but not in the example
below. How to make it work?

(we don't want to use pure OCaml option refs to store field values
before putting them into the record because that's too slow)

Requirements:
- performance is critical
- code will be machine-generated
- immutable record fields must be supported


The example below shows a record type for which a straight Obj.set_field
produces a field that cannot be read correctly with the usual dot
notation (ocamlopt only, tested on Linux/amd64 with OCaml 3.12.1 and
3.11.2).


$ ocamlopt -o foo.opt foo.ml; ./foo.opt
ERROR  t.foo is None
OK     field0

$ cat foo.ml
(* ocamlopt -o foo.opt foo.ml; ./foo.opt *)

type t = {
  foo : int option;
  bar : int;
}

let create () =
  { { foo = None; bar = 42 } with foo = None }

let () =
  assert (create () != create ());
  let t = create () in
  let f = Some 17 in
  Obj.set_field (Obj.repr t) 0 (Obj.repr f);

  let f1 = t.foo in
  let f2 = Obj.obj (Obj.field (Obj.repr t) 0) in

  if f1 = f then
    print_endline "OK     t.foo"
  else if f1 = None then
    print_endline "ERROR  t.foo is None"
  else
    print_endline "ERROR  t.foo is something strange";

  if f2 = f then
    print_endline "OK     field0"
  else if f2 = None then
    print_endline "ERROR  field0 is None"
  else
    print_endline "ERROR  field0 is something strange"

^ permalink raw reply	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2011-10-18 21:40 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2011-10-15  8:10 [Caml-list] How to mutate immutable record fields? Martin Jambon
2011-10-15  9:07 ` Nicolas Pouillard
2011-10-15  9:13 ` Jeremy Yallop
2011-10-15  9:15 ` Gabriel Scherer
2011-10-18 21:45   ` Martin Jambon

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).