Version française
Home     About     Download     Resources     Contact us    
Browse thread
Ocaml compiler features
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: skaller <skaller@u...>
Subject: Re: [Caml-list] Ocaml compiler features
On Tue, 2007-01-16 at 19:42 +0000, Jon Harrop wrote:
> On Tuesday 16 January 2007 17:47, skaller wrote:

> Choosing boxing and unboxing over exceptions is fine if you have that choice 
> and are willing to endure the performance degredation and added verbosity. 
> However, you only have that choice if your code is self-contained. If you're 
> writing a library where users can raise exceptions, you must be careful to 
> undo state changes. In OpenGL, for example:
> 
> let transform m k x =
>   GlMat.push();
>   GlMat.mult m;
>   try
>     k x;
>     GlMat.pop()
>   with e ->
>     GlMat.pop();
>     raise e
> 
> could be rewritten:
> 
> let transform m k x =
>   GlMat.push();
>   GlMat.mult m;
>   try k x finally
>   GlMat.pop()
> 
> Handling user-raised exceptions in this way is likely if you're using 
> higher-order functions.


Of course any specific example has a work around:

	let finally u f = try u () with e -> f (); raise e in

	let u () = GlMat.push(); GlMat.mult m in
	let f () = GlMat.pop() in
	finally u f

This would, however, be a mess if the push/pop things were
nested (which is likely I guess). Felix provides the syntax

	{ code here }

meaning Ocaml's

	(fun () -> code here)

which is very convenient for this idiom:

	finally { push GlMat; mult GlMat m; } { pop GlMat; };

More generally you can write:

	let f = new thing in
	let finally () = close f in
	try ... finally()
	with e -> finally(); raise e

which all gets very messy when you have to repeat the
exercise in the 'try' block for some other exception AND
in the 'new thing' code as well .. and it's a nightmare
if your 'finally()' code can ALSO raise an exception.. ;(


-- 
John Skaller <skaller at users dot sf dot net>
Felix, successor to C++: http://felix.sf.net