ocamlfinally

OCaml: finally clause related issues


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:

  1. the syntax of finally

  2. exn is a type, how can we use it in a pattern matching? Failed exn?

  3. Success (f x) matched with exn?

  4. relationship between cleanup and f x.


Solution

    1. 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
      
    2. 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

    3. Success (f x) is not returned if exception raises during evaluation f x.

    4. x is resource which you should free in finally branch, f does some work with created x