Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Immutable cyclic data structures via a
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Edgar Friendly <thelema314@g...>
Subject: Re: [Caml-list] Immutable cyclic data structures via a
Christopher L Conway wrote:
> This makes me wonder: if you add mutable fields to a type in order to
> build a cyclic data structure, but you intend to use the data
> structure immutably once it is built, is there any way to "freeze" the
> value, producing an immutable cyclic structure? This is a common
> pattern, similar to Bloch's Builder pattern for Java.[1]
> You might have an operation, call it "unmute", that changes the type
> of the structure. There would need to be a corresponding type-level
> operation, call it "UNMUTE", that strips the "mutable" qualifier from
> mutable fields. E.g.,
> I'm pretty confident this isn't possible in plain-vanilla OCaml. You
> can do something similar (at a high cost in ugliness) using a
> variation of "Tying the Knot" a la Haskell.[2]

ExtLib (and thus batteries) uses your unmute (called [inj]) for
converting a mutable list into the normal immutable list.  The definition:

external inj : 'a mut_list -> 'a list = "%identity"

It's effectively using Obj.magic, but specialized on these types.

As always, be *very* careful when using this kind of type system voodoo,
but it can work under certain circumstances.