English version
Accueil     Ŕ propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis ŕ jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml ŕ l'adresse ocaml.org.

Browse thread
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2009-04-04 (23:35)
From: Yaron Minsky <yminsky@g...>
Subject: Re: [Caml-list] Strings
On Sat, Apr 4, 2009 at 5:51 PM, Goswin von Brederlow <goswin-v-b@web.de>wrote:

> Mutable/Immutable can really nicely done with phantom types and is
> independent of the data structure used. It works for strings, lists,
> arrays, sets, trees, ... and I think all standard modules should have
> it. The official standard lib is rather lacking there but that is why
> there is Batteries. The more I hear/see of it the more I like it.

On this note, there's a small variation on this idea that we've experimented
with at Jane Street that I think is worth mentioning.  When people do this
kind of thing, they usually have two phantom tags, "immutable" and
"mutable", but, there is another natural one to add: "readonly".

A mutable value is, as one would expect, a value that can be modified; and
an immutable value is one that can not be modified.  A readonly value is one
that can not be modified, but that might change nonetheless because
somewhere else in the program there is a mutable handle to the same
underlying value.  You implement this by making the interface for immutable
and readonly values identical, except that a readonly value can be created
from a mutable value without copying.  Mutable and immutable are typically
the most important types of access control to implement, but readonly can be
useful in special cases, where you have a value that you really want to
mutate, but that you want to control where in the program the mutation can

There's one extra tradeoff worth mentioning with using phantom types for
controlling mutability, which is that values made immutable in this way are
not quite as good as values that are immutable at the lowest level.  The
reason is that ordinary immutable values are understood by the type system
as such, and this goes into the compiler's understanding of the value
restriction and variance.  This means there are cases where, say, a
phantom-immutable list won't work, but an ordinary immutable list will.

(For those interested in a short and elementary tutorial on how to implement
access control with phantom types, look here: