Version française
Home     About     Download     Resources     Contact us    
Browse thread
best and fastest way to read lines from a file?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Daniel_Bünzli <daniel.buenzli@e...>
Subject: Re: [Caml-list] best and fastest way to read lines from a file?

Le 1 oct. 07 à 23:27, YC a écrit :

> OCaml code:
> (* test.ml *)
> let rec line_count filename =
>   let f = open_in filename in
>   let rec loop file count =
>     try
>       ignore (input_line file);
>       loop file (count + 1)
>     with
>       End_of_file -> count
>   in
>     loop f 0;;

Your function is not tail recursive. A function is tail-recursive if  
there is nothing to do after the recursive call. You might believe  
this is the case in your function, but it is not the case because of  
the exception handler. Try this instead :

let rec line_count filename =
   let ic = open_in filename in
   let rec loop ic count =
    let line = try Some (input_line ic) with End_of_file -> None in
    match line with
    | Some _ -> loop ic (count+1)
    | None -> count
   in
   loop ic 0

It should run faster.

Daniel