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
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 (08:34)
From: Tiphaine Turpin <Tiphaine.Turpin@i...>
Subject: Re: [Caml-list] Preventing values from escaping a context
Jacques Garrigue a écrit :
> From: Rich Neswold <>
>> 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.
There is at least a partial solution using polymorhic records or other
ways of quantifying type variables inside a type expression : If you
artificially parameterise the type context with an unused parameter (and
hide the type definition), you can then require the argument function to
be polymorphic with respect to this parameter, which should prevent it
from returning or storing its argument.

However, it still allows Jacques Garrigue's example, if  there exists a
function chgCtx which takes any context (ignoring the parameter) and
does something with it. Maybe there is a way to type chgCtx so as to
prevent that ?


> 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
> _______________________________________________
> Caml-list mailing list. Subscription management:
> Archives:
> Beginner's list:
> Bug reports: