scsh-users
[Top] [All Lists]

Re: map function (tail recursive version)

To: scsh-users@scsh.net
Subject: Re: map function (tail recursive version)
From: pvk_google@pvk.ca (pkhuong)
Date: Sat, 24 Apr 2004 18:25:08 +0200 (MST)
List-id: <scsh-users.list-id.scsh.net>
Old-date: 24 Apr 2004 09:24:12 -0700
Organization: http://groups.google.com
alexis_o_torres@yahoo.com (aTorres) wrote in message 
news:<178146e3.0404232345.434b204c@posting.google.com>...
> I am new to scheme and am trying to implement useful recursive
> functions in to a tail recursive one. So far everything was ok, but
> now I am having trouble with making map a tail-recursive map.
[...]
> (define (map1 f l)
>   (if (NULL? l) '() (iter-map1 (list (f (car l))) f (cdr l))))
> 
> (define (iter-map1 curr f l)
>   (cond ((NULL? l) curr )
>         (else (iter-map1 (cons curr (f (car l))) f (cdr l)))))
> 
> => (map square ?(1 2 3 4 5))
> => (((((1) . 4) . 9) . 16) . 25)
> 
> Which have the correct elements in doted pairs. 
(BTW, could your variables have any LESS telling names?)

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). I guess you
could also use append if you didn't mind the very bad performance.

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