caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* [Caml-list] obj magic performance and other questions
@ 2011-03-15 16:05 Nicolas Ojeda Bar
  2011-03-15 17:17 ` Dario Teixeira
                   ` (3 more replies)
  0 siblings, 4 replies; 5+ messages in thread
From: Nicolas Ojeda Bar @ 2011-03-15 16:05 UTC (permalink / raw)
  To: caml-list

Hello,

I need to simulate, in Ocaml, the extensible records of Oberon. I am doing the
following:

Oberon type declaration:

TYPE

rec1 = RECORD a : INTEGER END;
rec2 = RECORD (rec1) b : CHAR END;
rec3 = RECORD (rec1) c : REAL END;

This means that variables of type rec2 or rec3 can be used
as variables of type rec1 and variables of type rec1 can be
downcasted at runtime to variables of type rec2 or rec3.

Ocaml code:

type rec2 = {
 b : char
}

type rec3 = {
 c : float
}

type rec123 =
| Rec1
| Rec2 of rec2
| Rec3 of rec3

type rec = {
 a : int;
 children : rec123
}

With this type declaration, upcasting from a rec2 or rec3 to a rec1 is simply
the identity function. Downcasting is obtained by a simple pattern match test:

let rec1_of_rec2 x = x

let rec2_of_rec1 x =
match x.children of
| Rec2 _ -> x | _ -> failwith "bad cast"

Now, if we are given a rec2 variable, and we want to access the field b,
we might have to do:

let rec2_b x =
match x.children with
| Rec2 r -> r.b
| _ -> assert false

This is not very efficient. I can use Obj.magic to access that same field as
follows:

let rec2_b x =
Obj.obj (Obj.field (Obj.field (Obj.repr x.children 0) 0))

My question is: is this use of Obj safe? and is this compiled to (two) simple
array accesses? Or is Obj.obj doing something behind the scenes?

Thanks!
N

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

end of thread, other threads:[~2011-03-17 16:36 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2011-03-15 16:05 [Caml-list] obj magic performance and other questions Nicolas Ojeda Bar
2011-03-15 17:17 ` Dario Teixeira
2011-03-16  2:21 ` Guillaume Yziquel
     [not found] ` <325023989.96091.1300242147328.JavaMail.root@zmbs4.inria.fr>
2011-03-16  8:46   ` Fabrice Le Fessant
2011-03-17 16:36 ` Damien Doligez

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).