Version française
Home     About     Download     Resources     Contact us    
Browse thread
Another try/finally idea
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jon Harrop <jon@f...>
Subject: Re: [Caml-list] Another try/finally idea
On Friday 28 December 2007 03:54:59 Dave Benjamin wrote:
> Here's another way of writing a HOF to do try/finally-like behavior to
> handle the allocation and disposal of resources. It's pretty similar to
> the one in Extlib, but it's designed to work well with the existing
> library functions:
>
> let using resource finalize process =
>    try
>      let result = process resource in
>      finalize resource;
>      result
>    with e ->
>      finalize resource;
>      raise e
>
> With this, I can print the first line of my .emacs file in one line:
>
> using (open_in ".emacs") close_in input_line
>
> Common cases can be wrapped easily:
>
> let with_open_in filename = using (open_in filename) close_in
> let with_open_in_bin filename = using (open_in_bin filename) close_in
> let with_open_out filename = using (open_out filename) close_out
> let with_open_out_bin filename = using (open_out_bin filename) close_out
>
> Now, getting the first line is even simpler (and more readable):
>
> with_open_in ".emacs" input_line

Yes, that is essentially what I use except I discard any exception thrown by 
your second call to "finalize".

However, perhaps an even better solution would be a camlp4 macro and emacs 
support for F#'s "use" notation:

  use ch = open_in ".emacs" in
  input_line ch

This closes at the end of scope. Of course, we'd need some kind of homogeneous 
disposal and the easiest solution would be to copy .NET again by wrapping 
resources in an object that has a dispose method.

-- 
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/products/?e