[plt-scheme] sicp exercise 2.23

From: Jason Wang (randomtalk at gmail.com)
Date: Tue Apr 29 02:04:28 EDT 2008

Hey guys, i was just working through SICP book after having (pretty
much) completed HtDP in school. I have  a question about 2.23 exercise
reproduced here:

Exercise 2.23.  The procedure for-each is similar to map. It takes as
arguments a procedure and a list of elements. However, rather than
forming a list of the results, for-each just applies the procedure to
each of the elements in turn, from left to right. The values returned
by applying the procedure to the elements are not used at all --
for-each is used with procedures that perform an action, such as
printing. For example,

(for-each (lambda (x) (newline) (display x))
          (list 57 321 88))

The value returned by the call to for-each (not illustrated above) can
be something arbitrary, such as true. Give an implementation of
Using begin, this problem is quite simple, as below:
(define (for-each fun items)
  (cond [(not (null? items))
           (fun (car items))
           (for-each fun (cdr items)))]))
(for-each (lambda (x) (newline) (display x))
          (list 57 321 88))

However, my problem is that SICP hasn't introduced begin yet, so i
looked around online and saw someone else's solution as follows:
(define (for-each2 fun items)
  (cond [(not (null? items))
         (fun (car items))
         (for-each2 fun (cdr items))]))
(for-each2 (lambda (x) (newline) (display x))
          (list 57 321 88))

It works as well, but can someone tell me why it works and if i did
the following (which i thought is equivalent to the second one) and it
wouldn't work:
(define (for-each3 fun items)
  (if (not (null? items))
      (fun (car items))
      (for-each3 fun (cdr items))))
(for-each3 (lambda (x) (newline) (display x))
          (list 57 321 88))

Also why do we learn begin if one of the last 2 works.

On a side note, the test code is provided in the book, and in the
lambda expression, the author didn't use begin either....

Thanks a lot for any clarifications provided :D


"It's a wonderful world hobbes ol' buddy, let's go explorin'!" -
Calvin in "Calvin and Hobbes"

Posted on the users mailing list.