[plt-scheme] sicp exercise 2.23

From: Doug Orleans (dougorleans at gmail.com)
Date: Tue Apr 29 22:30:30 EDT 2008

I'm guessing this is not the solution they had in mind:

(define (for-each proc items)
  (map proc items)

Jason Wang writes:
 > On Tue, Apr 29, 2008 at 2:03 AM, Jos Koot <jos.koot at telefonica.net> wrote:
 > >  The above form of cond has not yet been introduced either before reaching
 > > problem 2.23. Look at how you would implement map, then decide what to
 > > discard.
 > Well, in the book, they implemented map as follows:
 > (define (map proc items)
 >   (if (null? items)
 >       nil
 >       (cons (proc (car items))
 >             (map proc (cdr items)))))
 > I think you have to discard the cons form but other than the cond
 > implementation mentioned before, i'm not sure how to proceed to
 > implement it.

Instead of discarding the cons, try replacing it with your own helper
procedure.  I suspect that's the solution they had in mind, but
there's a subtle problem: the Scheme standard does not specify that
arguments are evaluated from left to right (although PLT Scheme does
guarantee that), which means that in some Scheme implementations the
items might not be displayed in order.  Using begin (which is a
special form, and thus does not evaluate its arguments) would get
around this, but the more general solution for fixing the order of
evaluation is to use let:

(define (for-each proc items)
  (if (null? items)
      (let ((ignored-value (proc (car items))))
        (for-each proc (cdr items)))))

Or you could be even more explicit and use let*:

(define (for-each proc items)
  (if (null? items)
      (let* ((ignored-value1 (proc (car items)))
             (ignored-value2 (for-each proc (cdr items))))

But note that this is not tail-recursive (unless the compiler is
smarter than I think it is).

 > On Tue, Apr 29, 2008 at 12:35 PM, John Clements <clements at brinckerhoff.org> wrote:
 > >  I don't have a copy of SICP handy

Sure you do: http://mitpress.mit.edu/sicp/full-text/book/book.html

--dougorleans at gmail.com

Posted on the users mailing list.