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
Ocaml compiler features
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2007-01-17 (13:18)
From: tab@s...
Subject: Re: [Caml-list] Ocaml compiler features
On Wed, Jan 17, 2007 at 01:53:47PM +0100, Olivier Andrieu wrote:
> that's not clear-cut ; it depends on the cleanup function. For
> instance, concerning I/O channels in the standard library, you have
> close_out and close_out_noerr. They do not have the same behavior, and
> you should rather use the _no_err one in the with exn part.

You're right it's not clear-cut, but I'm talking about generic code.

Some function doesn't have the opportunity to not raise something
(without bracing them in try fct () with _ -> ()) and sometimes you also
want to propagate the cleanup's fct exception .. because something went
very wrong.

> >the point is not it's hard to do, it's annoything to duplicate here and
> >there, and doing the inline code lose the higher level view we can have
> >with a syntaxic sugar like try-finally.
> Just use a higher-order function: it won't duplicate code, it's
> high-level and it doesn't require any syntactic sugar.

Please read what I wrote before replying. The higher order function is
what I do now, because there's no other way for the code I use. It's *not*
hard to do and I already have lots of code that just look like your
example functions.

That said, it's just would be *easier* to express the "concept" with
appropriate keyword, not *emulated* through try-with.

> let with_file_out fname f =
>  let oc = open_out fname in
>  try let r = f oc in close_out oc ; r
>  with exn -> close_out_noerr oc ; raise exn

This one doesn't have equivalent with finally, but that's fine
it cannot cover everything.
But *most* of the time the cleanup function is similar in both case.

> let with_mat m f =
>  GlMat.push () ;
>  let r =
>    try GlMat.mult m ; f ()
>    with exn -> GlMat.pop () ; raise exn in
>  GlMat.pop () ;
>  r

This become:

let with_mat m f =
	GlMat.push ();
	try GlMat.mult m ; f (); finally GlMat.pop ()

I can see in a jiffie what the second function does.
It's not as clear with the first one, I need to read a bit more to see
what it does (and GlMat.pop has been duplicated)

Vincent Hanquez