From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from mail1-relais-roc.national.inria.fr (mail1-relais-roc.national.inria.fr [192.134.164.82]) by walapai.inria.fr (8.13.6/8.13.6) with ESMTP id p9F9D8tJ006894 for ; Sat, 15 Oct 2011 11:13:08 +0200 X-IronPort-Anti-Spam-Filtered: true X-IronPort-Anti-Spam-Result: Aq4BANFNmU7RVdK2kWdsb2JhbABDqF0IIgEBAQEJCQ0HEieBbgEBAQMBEgIsARsdAQMBCwYFCw0uIgERAQUBHAYTCBqHXZlaCotRgmCEdT2IbgIFCod6BJN6jSo9g3A X-IronPort-AV: E=Sophos;i="4.69,350,1315173600"; d="scan'208";a="124230897" Received: from mail-iy0-f182.google.com ([209.85.210.182]) by mail1-smtp-roc.national.inria.fr with ESMTP/TLS/RC4-SHA; 15 Oct 2011 11:13:03 +0200 Received: by iaky10 with SMTP id y10so5961156iak.27 for ; Sat, 15 Oct 2011 02:13:02 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=gamma; h=mime-version:in-reply-to:references:date:message-id:subject:from:to :cc:content-type:content-transfer-encoding; bh=+etmumlPGz1VcfuFurYgq9oC1kOBl5ITLLdGIBXFGEE=; b=M/dCP2ppo1HCrTFP33TpFXbl9zmTk81Awo6NPOkCHyV2njkB0nnrPBvAOD/t2KRhp6 WseC9OaBtyDzI7HrPX0ZDqx9B+vNh7sulRWL6BXBxx7XFXtkKkHJi4oEYEYpeQaE/HYn /LkDNUQ4xC2ikInhRKdn96rdnpSY9V8wFnN+0= MIME-Version: 1.0 Received: by 10.231.5.102 with SMTP id 38mr1172402ibu.98.1318669981917; Sat, 15 Oct 2011 02:13:01 -0700 (PDT) Received: by 10.231.199.5 with HTTP; Sat, 15 Oct 2011 02:13:01 -0700 (PDT) In-Reply-To: <4E993FE5.7080409@ens-lyon.org> References: <4E993FE5.7080409@ens-lyon.org> Date: Sat, 15 Oct 2011 10:13:01 +0100 Message-ID: From: Jeremy Yallop To: Martin Jambon Cc: OCaml Mailing List Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit X-MIME-Autoconverted: from quoted-printable to 8bit by walapai.inria.fr id p9F9D8tJ006894 Subject: Re: [Caml-list] How to mutate immutable record fields? On 15 October 2011 09:10, Martin Jambon wrote: > 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 way I've approached this in the past is to to construct the record at a mutable version of the type, then convert the value to the immutable type at the last moment. That is, for your type > type t = { >  foo : int option; >  bar : int; > } I'd have the serialisation code generate a second type, not exposed to user code: module Mutable = struct type mutable_t = { mutable foo : int option; mutable bar : int; } end The generated deserialisation code would deal only with values of type Mutable.t, concluding with a final coercion (Obj.magic) to the exposed type t.