Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] Resource acquisition is initialization
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Dmitry Bely <dbely@m...>
Subject: Re: [Caml-list] Resource acquisition is initialization
Xavier Leroy <> writes:

>> One of the nice things about C++ and Java is that with properly
>> designed classes, you don't need to worry about freeing resources
>> in complicated code, because the when the objects go out of scope
>> either normally or via an exception, they will clean themselves up.
> I believe this is a C++-specific idiom.  Java doesn't have
> destructors, just finalizers that are called asynchronously by the
> GC.  OCaml also has GC finalization (see below).
>> Given that Ocaml has objects, it would be useful to have this
>> idiom available to us.  Is there a way to implement it, rather
>> than just waiting for the garbage collector?
> Yes: higher-order functions.  For a file:
> let with_file_in filename action =
>   let ic = open_in filename in
>   try
>     let res = action ic in close_in ic; res
>   with x ->
>     close_in ic; raise x

Maybe I don't understand something but IMHO it's not very usable because
with_file_in type is fixed after the first use. So e.g. input_line and
input_char operation cannot be mixed. You cannot write something like

let process filename =
  let f = with_file_in filename in
       print_string (f input_line);
       print_char   (f input_char); (* syntax error! *)

- Dmitry Bely

To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: