[
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: | tim@f... |
| Subject: | Re: [Caml-list] closing file descriptors and channels |
From: "Christian Schaller" <Christian.Schaller@siemens.com>
>Yup, I've seen this one already. This one makes it complicated, since
>for propagating the exception, I have to duplicate the closings:
>
> .
> .
> .
> with
> End_of_file -> output_string oc (line ^ "\n");
> Found line -> (close_out oc; close_in ic; raise Found line);
> close_out oc;
> close_in ic
Java's "try ... finally" is useful and can be recreated in ML. Here's
a definition:
let finally (body: unit -> 'a) (handler: unit -> unit): 'a =
let result: 'a option ref = ref None
in begin
begin
try begin
result := Some (body ());
end with e -> begin
handler ();
raise e;
end;
end;
handler ();
match !result with
Some r -> r
| _ -> failwith "Confused in finally";
end;;
and here's how to use it for your example:
let ic = "open the input file somehow" in
finally (fun () ->
let oc = "open the output file somehow" in
finally (fun () ->
.
. (sometimes raise Found somewhere in here)
.
with
End_of_file -> output_string oc "whatever")
(fun () -> close_out oc))
(fun () -> close_in ic)
I have to admit Java's syntax for try...finally is better.
--
Tim Freeman tim@fungible.com
GPG public key fingerprint ECDF 46F8 3B80 BB9E 575D 7180 76DF FE00 34B1 5C78
Your levity is good. It relieves tension and fear of death. -- Terminator 3
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners