caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* Another try/finally idea
@ 2007-12-28  3:54 Dave Benjamin
  2007-12-28  4:09 ` [Caml-list] " Jon Harrop
  0 siblings, 1 reply; 2+ messages in thread
From: Dave Benjamin @ 2007-12-28  3:54 UTC (permalink / raw)
  To: caml-list

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

Dave


^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2007-12-28  4:19 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2007-12-28  3:54 Another try/finally idea Dave Benjamin
2007-12-28  4:09 ` [Caml-list] " Jon Harrop

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).