Re: OCaml and tail recursion

From: Alain Frisch (frisch@clipper.ens.fr)
Date: Tue Dec 14 1999 - 16:32:40 MET


Date: Tue, 14 Dec 1999 16:32:40 +0100 (MET)
From: Alain Frisch <frisch@clipper.ens.fr>
To: Norman Ramsey <nr@eecs.harvard.edu>
Subject: Re: OCaml and tail recursion
In-Reply-To: <199912131727.MAA20344@labrador.eecs.harvard.edu>

On Mon, 13 Dec 1999, Norman Ramsey wrote:

> [snip]
> Apparently ocamlc doesn't optimize tail calls.

Yes it does. It is difficult to help if you don't give the code or its
structure. If you build a list with the characters you parse, consider
rewriting a code like :

let rec map f = function
 | h::t -> (f h)::(m f t)
 | _ -> []

(which is not tail recursive)

into something like:

let rec map f l =
 let rec aux accu = function
 | h::t -> aux ((f h)::accu) t
 | _ -> []
 in
 List.rev (aux [] l)

(List.rev is tail recursive)

Alain



This archive was generated by hypermail 2b29 : Sun Jan 02 2000 - 11:58:29 MET