scsh-users
[Top] [All Lists]

Re: map function (tail recursive version)

To: scsh-users@scsh.net
Subject: Re: map function (tail recursive version)
From: Rick Hanson <rick@tamos.net>
Date: Tue, 27 Apr 2004 08:39:51 -0400 (EDT)
List-id: <scsh-users.list-id.scsh.net>
On Sat, 24 Apr 2004, [ISO-8859-1] Jens Axel Søgaard wrote:

> pkhuong wrote:
>
> > The idiomatic way of doing this in Common Lisp (I can't believe the
> > Scheme way is that different), is to push (ie (cons data acc)) data on
> > the accumulator (curr) and to return the accumulator, /reversed/
> > (nreverse, but i don't suppose that's included in R5RS).
>
> It's called reverse! in the Scheme world. It is specified in SRFI1.
>
>      <http://srfi.schemers.org/srfi-1/srfi-1.html>
>
> --
> Jens Axel Søgaard
>

Sorry to enter late into the discussion, but in short, all these guys are
right.  And I'd like to add a small comment.  You might try writing the
map this way:

(define (tr-map f lst)
  (let recur ((rest lst) (acc '()))
    (if (null? rest)
        (reverse acc)
        (recur (cdr rest) (cons (f (car rest)) acc)))))

At least then you could take advantage of lexical scoping and not have to
pass around the function ('f' in this case).

Also Jens's recommendation to use the destructive reverse (i.e.
'reverse!') is I think a good one.  If coded correctly, it should be
faster then 'reverse' (which I used in the example above).

Hope that helps.  Cheers!  --Rick

<Prev in Thread] Current Thread [Next in Thread>