From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from mail3-relais-sop.national.inria.fr (mail3-relais-sop.national.inria.fr [192.134.164.104]) by walapai.inria.fr (8.13.6/8.13.6) with ESMTP id p2FG5dOK006308 for ; Tue, 15 Mar 2011 17:05:39 +0100 X-IronPort-Anti-Spam-Filtered: true X-IronPort-Anti-Spam-Result: AjkFAIIrf02M9xyZi2dsb2JhbACZCY0TAQEBCgsLGyW6AYhrgnyCZgSMXQ X-IronPort-AV: E=Sophos;i="4.62,322,1297033200"; d="scan'208";a="78172048" Received: from math.harvard.edu (HELO abel.math.harvard.edu) ([140.247.28.153]) by mail3-smtp-sop.national.inria.fr with ESMTP; 15 Mar 2011 17:05:35 +0100 Received: from dhcp-0153398808-58-7c.client.student.harvard.edu (wrls-249-210-92.wrls-client.fas.harvard.edu [140.247.253.92]) (using TLSv1 with cipher AES128-SHA (128/128 bits)) (No client certificate requested) by abel.math.harvard.edu (Postfix) with ESMTP id BE21EA697 for ; Tue, 15 Mar 2011 12:05:32 -0400 (EDT) From: Nicolas Ojeda Bar Content-Type: text/plain; charset=us-ascii Date: Tue, 15 Mar 2011 12:05:31 -0400 Message-Id: <057400AC-9E39-45CC-AB7A-35C67C339F83@math.harvard.edu> To: caml-list@yquem.inria.fr Mime-Version: 1.0 (Apple Message framework v1082.1) X-Mailer: Apple Mail (2.1082.1) Content-Transfer-Encoding: 8bit X-MIME-Autoconverted: from quoted-printable to 8bit by walapai.inria.fr id p2FG5dOK006308 Subject: [Caml-list] obj magic performance and other questions 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