Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Frustrated Beginner
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Oleg Trott <oleg_trott@c...>
Subject: Re: [Caml-list] Frustrated Beginner
On Tuesday 23 December 2003 06:01 am, Dustin Sallings wrote:
> On Dec 23, 2003, at 2:26, Samuel Lacas wrote:
> > May be
> >
> > http://pleac.sourceforge.net/pleac_ocaml.html
> >
> > may help you here.
>
> 	Interesting, this has the same problem I had when I tried to create
> fold_lines:
>
> let rec fold_lines f init chan =
>    try
>      let line = input_line chan in
>      fold_lines f (f init line) chan
>    with End_of_file -> init
>
> 	That ends up not being tail recursive.  I suppose I should get on the
> list and try to make some suggestions.

Non-recursive version

let fold_lines f init chan =
   let res = ref init in
   (try while true do
      res  := f !res (input_line chan)
   done with End_of_file -> ());
   !res

Tail-recursive version:

let rec fold_lines f init chan =
   match try Some (input_line chan) with End_of_file -> None with
   | Some line -> fold_lines f (f init line) chan
   | None -> init

(But I don't think "fold" functions are useful for a beginner, especially one 
who's still having problems with the syntax aspect of the language. TE, look 
elsewhere)

-- 
Oleg Trott <oleg_trott@columbia.edu>

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