English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
[Caml-list] Why do input* and readdir throw End_of_file ... annoying!
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2003-06-06 (18:32)
From: Brian Hurt <brian.hurt@q...>
Subject: Re: [Caml-list] Why do input* and readdir throw End_of_file ... annoying!
On Fri, 6 Jun 2003, Ville-Pertti Keinonen wrote:

> Since exceptions are reasonably inexpensive in O'Caml, and used for 
> things such as Not_found in basic collection types, using exceptions to 
> indicate the end of some particular set of values seems reasonable, to 
> me.
> Writing a try ... with statement isn't really that different from a 
> match statement except for the fact that you can handle exceptional 
> circumstances generated by several expressions in the with ... part of 
> a try ... with statement - if anything, that's more permissive.

The problem with try/with is that it's way to easy to break tail recursion 
using try/with.  About every other week someone comes to the Ocaml 
beginners list where they are doing something like:

let rec read_all_lines chan accum =
       let line = input_line chan in
       read_all_lines chan (line :: accum)
      End_of_file -> List.rev accum

Unfortunately, this is *not* tail recursive.  Works fine on small files,
but when they try to run it on large files they stack overflow.  Which
means you need to contort to take the recursion out of the try/with block.
Several different approaches to this are possible- but none with the 
obviousness of the above code.

Personally, I'd like the following to be an efficient way to read all the 
lines from a file into a list:

let rec read_all_lines chan =
         let line = input_line chan in
         line :: (read_all_lines chan)
         End_of_file -> []

and have the compiler contort the code into an efficient, tail-recursive 
form, with a combination of data structures with a hole and catch removal.


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