From mboxrd@z Thu Jan 1 00:00:00 1970 Received: (from majordomo@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id OAA04728; Thu, 12 Dec 2002 14:17:08 +0100 (MET) X-Authentication-Warning: pauillac.inria.fr: majordomo set sender to owner-caml-list@pauillac.inria.fr using -f Received: from concorde.inria.fr (concorde.inria.fr [192.93.2.39]) by pauillac.inria.fr (8.7.6/8.7.3) with ESMTP id OAA04637 for ; Thu, 12 Dec 2002 14:17:07 +0100 (MET) Received: from pauillac.inria.fr (pauillac.inria.fr [128.93.11.35]) by concorde.inria.fr (8.11.1/8.11.1) with ESMTP id gBCDF7X09903; Thu, 12 Dec 2002 14:15:07 +0100 (MET) Received: (from xleroy@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id OAA04655; Thu, 12 Dec 2002 14:15:06 +0100 (MET) Date: Thu, 12 Dec 2002 14:15:06 +0100 From: Xavier Leroy To: Blair Zajac Cc: Caml Users Mailing List Subject: Re: [Caml-list] Resource acquisition is initialization Message-ID: <20021212141506.A24877@pauillac.inria.fr> References: <3DF78FB5.A1642B8@orcaware.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Mailer: Mutt 1.0i In-Reply-To: <3DF78FB5.A1642B8@orcaware.com>; from blair@orcaware.com on Wed, Dec 11, 2002 at 11:19:17AM -0800 Sender: owner-caml-list@pauillac.inria.fr Precedence: bulk > 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 For a mutex: let synchronize mut action = try Mutex.lock mut; let res = action () in Mutex.unlock mut; res with x -> Mutex.unlock mut; raise x You get the idea. > Also, since objects have initializers, do they have finializers? I > read the entire Oreilly book and didn't see any mention of them. > Reading the C code interface, it looks like you can associate a > finalizer function to clean up an abstract type, but can you do > this with normal Ocaml code? Yes. The function Gc.finalise lets you attach finalization code to any heap-allocated Caml value, not just objects. I'm not surprised it is not mentioned in the O'Reilly book, since this is a recent addition to the OCaml implementation. - Xavier Leroy ------------------- To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/ Beginner's list: http://groups.yahoo.com/group/ocaml_beginners