Destroy After Use

Exceptions make the control flow of a program quite complex, since any call could possibly create an exception and thus leave the currently executing function. Even with a garbage collector, certain resources (such as files) have to be manually released. Some languages use destructors and RAII (for instance, C++) to handle scope-based release, others use an explicit using(){} or finally {} block to also add a scope to such resources.

None of this exists in OCaml.

It can be rather easily reconstructed using existing language semantics, however:

let scoped user resource clean =
  try
    let result = user resource in
    clean resource ;
    result
  with exn ->
    clean resource ;
    raise exn 

let with_input name f =
  scoped f (open_in_bin name) close_in 

let with_output name f =
  scoped f (open_out_bin name) close_out

0 Responses to “Destroy After Use”


  1. No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



706 feed subscribers
(readers who polled a feed this week)