From: Remi Vanicat <vanicat@labri.u-bordeaux.fr>
To: caml-list@pauillac.inria.fr
Subject: Re: [Caml-list] beginner question about tail recursion
Date: Sun, 31 Aug 2003 11:12:44 +0200 [thread overview]
Message-ID: <87znhqw5pv.dlv@wanadoo.fr> (raw)
In-Reply-To: <20030831063334.GA3405@swordfish> (Matt Gushee's message of "Sun, 31 Aug 2003 00:33:35 -0600")
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
next prev parent reply other threads:[~2003-08-31 9:11 UTC|newest]
Thread overview: 6+ messages / expand[flat|nested] mbox.gz Atom feed top
2003-08-30 22:52 Ram Bhamidipaty
2003-08-31 6:33 ` Matt Gushee
2003-08-31 9:12 ` Remi Vanicat [this message]
2003-08-31 15:53 ` Matt Gushee
2003-08-31 10:31 ` skaller
2003-08-31 10:06 ` [Caml-list] beginner question about tail recursion (caml: addressed to trusted sender for this address) Warren Harris
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=87znhqw5pv.dlv@wanadoo.fr \
--to=vanicat@labri.u-bordeaux.fr \
--cc=caml-list@pauillac.inria.fr \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox