From mboxrd@z Thu Jan 1 00:00:00 1970 Received: (from majordomo@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id LAA10334; Sun, 31 Aug 2003 11:11:11 +0200 (MET DST) X-Authentication-Warning: pauillac.inria.fr: majordomo set sender to owner-caml-list@pauillac.inria.fr using -f Received: from concorde.inria.fr (concorde.inria.fr [192.93.2.39]) by pauillac.inria.fr (8.7.6/8.7.3) with ESMTP id LAA13296 for ; Sun, 31 Aug 2003 11:11:10 +0200 (MET DST) Received: from mwinf0202.wanadoo.fr (smtp7.wanadoo.fr [193.252.22.29]) by concorde.inria.fr (8.11.1/8.11.1) with ESMTP id h7V9BAf20093 for ; Sun, 31 Aug 2003 11:11:10 +0200 (MET DST) Received: from debian (ca-bordeaux-5-19.w80-8.abo.wanadoo.fr [80.8.77.19]) by mwinf0202.wanadoo.fr (SMTP Server) with ESMTP id 03853A400167 for ; Sun, 31 Aug 2003 11:11:10 +0200 (CEST) Received: from moi by debian with local (Exim 3.36 #1 (Debian)) id 19tOGK-0004id-00 for ; Sun, 31 Aug 2003 11:12:44 +0200 To: caml-list@pauillac.inria.fr Subject: Re: [Caml-list] beginner question about tail recursion References: <20030831063334.GA3405@swordfish> From: Remi Vanicat Mail-Copy-To: never In-Reply-To: <20030831063334.GA3405@swordfish> (Matt Gushee's message of "Sun, 31 Aug 2003 00:33:35 -0600") User-Agent: Gnus/5.090024 (Oort Gnus v0.24) Emacs/21.3 (gnu/linux) Date: Sun, 31 Aug 2003 11:12:44 +0200 Message-ID: <87znhqw5pv.dlv@wanadoo.fr> MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-15 Content-Transfer-Encoding: 8bit X-Loop: caml-list@inria.fr X-Spam: no; 0.00; caml-list:01 recursion:01 gushee:01 gushee:01 unmodified:01 unmodified:01 rec:01 rec:01 dept-info:01 labri:01 labri:01 u-bordeaux:01 u-bordeaux:01 writes:01 remi:01 Sender: owner-caml-list@pauillac.inria.fr Precedence: bulk Matt Gushee 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