Note: this wiki is now retired and will no longer be updated!

The static final versions of the pages are left as a convenience for readers. Note that meta-pages such as "discussion," "history," etc., will not work.

SICP exercise 2.23

From Drewiki
Jump to: navigation, search

Problem

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))

Output:

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 for-each.

Solution

Here's one implementation. This one prints a newline character when it reaches the end of the list, which makes the output a bit prettier. (This probably isn't a good idea for a real for-each implementation!)

(define (for-each f items)
  (if (null? items)
      (newline)
      (let ()
        (f (car items))
        (for-each f (cdr items)))))

Test:

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

Output:

57
321
88
Personal tools