type 'a result =
Success of 'a
| Failed of exn
let finally f x cleanup =
let result =
try Success (f x) with
exn -> Failed exn
in
cleanup ();
match result with
Success y -> y
| Failed exn -> raise exn
There are several places I do not understand:
the syntax of finally
exn is a type, how can we use it in a pattern matching? Failed exn?
Success (f x) matched with exn?
relationship between cleanup and f x.
It is supposed that use will use finally something like that:
let h = open_db () in
let f db = ... return someting from db in
let res = finally f h (fun () -> close_db h) in
exn is a type but name spaces for types and values are almost not mixing in OCaml. So, when you write Failed exn
exn
is name binding
Success (f x)
is not returned if exception raises during evaluation f x
.
x
is resource which you should free in finally branch, f
does some work with created x