caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
From: Damien Doligez <damien.doligez@inria.fr>
To: OCaml List <caml-list@yquem.inria.fr>
Subject: Re: [Caml-list] tip for tail recursive map
Date: Mon, 2 Nov 2009 11:33:30 +0100	[thread overview]
Message-ID: <8F7FB895-BC42-49C6-BAB3-4EDDF761C78B@inria.fr> (raw)
In-Reply-To: <f3b7783f0910231255r65df6037s528471ac57c1a18a@mail.gmail.com>


On 2009-10-23, at 21:55, pikatchou pokemon wrote:

> I know this topic has been discussed several times, but I don't  
> think I have seen the solution I use for functions of the List  
> module which are not tail recursive.
> I thought sharing the tip could be nice.
> I will take an example, List.map.
> When rewritten in CPS map becomes:
>
> let rec map k f = function
>   | []    -> k []
>   | x :: rl -> map (fun res -> k ((f x) :: res)) f rl

You can do better with an ad-hoc encoding of the continuation
instead of using closures:

let rec map k f = function
   | [] -> List.rev k
   | x :: rl -> map (f x :: k) f rl
;;

The memory footprint is smaller, and you spend much less time
invoking closures.

Note that I haven't bothered benchmarking these two functions.

-- Damien


  reply	other threads:[~2009-11-02 10:33 UTC|newest]

Thread overview: 7+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2009-10-23 19:55 pikatchou pokemon
2009-11-02 10:33 ` Damien Doligez [this message]
2009-11-02 19:56   ` [Caml-list] " Julien Verlaguet
2009-11-02 20:04     ` Christophe Raffalli
2009-11-03  1:29       ` Yaron Minsky
2009-11-02 20:00   ` Christophe Raffalli
2009-11-02 23:30     ` Jon Harrop

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=8F7FB895-BC42-49C6-BAB3-4EDDF761C78B@inria.fr \
    --to=damien.doligez@inria.fr \
    --cc=caml-list@yquem.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;
as well as URLs for NNTP newsgroup(s).