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
Preventing values from escaping a context
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2010-02-09 (03:38)
From: Jacques Garrigue <garrigue@m...>
Subject: Re: [Caml-list] Preventing values from escaping a context
From: Rich Neswold <rich.neswold@gmail.com>

> Most of the functions in my library take a parameter that describes the
> current environment. I call this data type, "context". The context is passed
> to a function which will then use other functions in the library to get its
> job done. The signature of the function that starts all this is:
> val usingContext : (context -> 'a) -> 'a
> My question is this: Is there a way to make the compiler reject a function
> parameter from returning the context parameter? For instance, the identity
> function should be disallowed since the context is invalid outside the scope
> of 'usingContext'. It's true that a returned context would be unusable,
> since its resources are gone, but it would be nice to prevent contexts from
> escaping the 'usingContext' function entirely.

The short answer is no.
Types are not sufficient to prevent values from escaping.
In ocaml, you have both functions and references.
So you can always plug a function of type [unit -> unit] into a
reference, and the function is allowed to access the full context
available when it was created.

let r = ref (fun () -> ())

let f ctx =
  r := (fun () -> chgCtx ctx)

(* later on *)

List.hd !r ()

The language is just too expressive...
You should rather look into adding a dynamic flag to your context,
causing a runtime error if you use it later.

Jacques Garrigue