Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] beginner question about tail recursion
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Remi Vanicat <vanicat@l...>
Subject: Re: [Caml-list] beginner question about tail recursion
Matt Gushee <matt@gushee.net> writes:

[...]

> A tail-recursive way to write the function would be:
>
>   let rec readlines chnl lines =
>     let line, eof =
>       try
>         let ln = input_line chnl in
>         ln, false
>       with End_of_file ->
>         [], true in
>     if eof then lines            (* result returned unmodified *)
>     else readlines chnl (line :: lines)
>                                  (* 'line :: lines' is evaluated before
>                                     applying 'readlines' *)

well, this code is tail-recursive, but it is not correct (it won't
compile). This one is better :

let rec readlines chnl lines =
    let maybe_line =
      try
        let ln = input_line chnl in
        Some ln
      with End_of_file ->
        None in
    match maybe_line with
    | Some line -> readlines chnl (line :: lines)
                                 (* 'line :: lines' is evaluated before
                                    applying 'readlines' *)
    | None -> lines            (* result returned unmodified *)

by the way, the lines in the returned list will be in the reversed
order. 
[...]


-- 
Rémi Vanicat
vanicat@labri.u-bordeaux.fr
http://dept-info.labri.u-bordeaux.fr/~vanicat

-------------------
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