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”