%finally example

,

Sorry for novice question but I need some help converting old code:

try_lwt
   foo bar
finally
    LTerm_ui.quit ui

to use ppx try%lwt and %finally syntax and could not make it work. How the code above should be rewritten?

Thanks!

P.S. I do not need to catch/process exceptions. Just need to make sure finally block is always exectured.

Lwt.finalize is what you’re looking for

I know Lwt.finalize and used it as a workaround. I wanted to see if there is a way to use PPX extension to make look nicer. lwt.ppx documtnatoion mentions both lwt%try and %finally.

@vzaliva there is an example in the proposed new module Lwt docs here:


let () =
  Lwt_main.run begin
    let%lwt file = Lwt_io.(open_file Input "code.ml") in
    begin
      let%lwt content = Lwt_io.read file in
      Lwt_io.print content
    end
    [%lwt.finally
      Lwt_io.close file]
  end

(* ocamlfind opt -linkpkg -package lwt.ppx,lwt.unix code.ml && ./a.out *)

This doesn’t actually use try%lwt, because it’s not necessary to use with %lwt.finally. By the way, you should always use it as %lwt.finally, not just %finally.

To use with try%lwt, you’d put a try%lwt expression in the inner begin...end. If you consider begin...end to be ugly, like many people do, you can use ordinary parentheses instead.

Yes, that helped! Thanks @antron. Apparently square bracked around lwt.finally is what required. Would you care to explain to me the magic? Why square brackets? Is this ppx thing? Is it specific to lwt.ppx? Just curious.

The words lwt.finally are Lwt-specific, of course, but the rest is the standard PPX API. You may benefit from reading these:

There is also a discussion of why this syntax was chosen for Lwt here.

Basically, expression attributes (expr [%...attribute...]) are the only good way to attach PPX syntax to expressions. That’s why it was chosen, so that lwt.finally is associated with one expression. We can’t freely add a new keyword, as could be done in Camlp4.

1 Like