[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Dave Benjamin <dave@r...> |
| Subject: | Another try/finally idea |
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