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: Matt Gushee <matt@g...>
Subject: Re: [Caml-list] beginner question about tail recursion
On Sun, Aug 31, 2003 at 11:12:44AM +0200, Remi Vanicat wrote:
> 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 :

Oops. You're right. Although I use this technique myself, apparently I
have never done exactly what I wrote above. Sorry.

> let rec readlines chnl lines =
>     let maybe_line =
>       try
>         let ln = input_line chnl in
>         Some ln

Oh, I like that. Thanks.

-- 
Matt Gushee                 When a nation follows the Way,
Englewood, Colorado, USA    Horses bear manure through
mgushee@havenrock.com           its fields;
http://www.havenrock.com/   When a nation ignores the Way,
                            Horses bear soldiers through
                                its streets.
                                
                            --Lao Tzu (Peter Merel, trans.)

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