[plt-scheme] sicp exercise 2.23

From: Shawn Tice (0x6d65 at gmail.com)
Date: Tue Apr 29 15:50:02 EDT 2008

On Apr 28, 2008, at Apr 28, 11:04:28 PM, Jason Wang wrote:
> However, my problem is that SICP hasn't introduced begin yet

The book has introduced sequences of expressions evaluated for side  
effects, at least in passing. Notice that the below definition (from  
exercise 1.22) has three expressions in its body, and that none of  
their values are used.

(define (timed-prime-test n)
   (display n)
   (start-prime-test n (runtime)))

Using that concept and internal definitions, also introduced in  
chapter 1, you can define for-each as:

(define (my-for-each f lst)
   (define (side-effect-and-continue)
     (f (car lst))
     (my-for-each f (cdr lst)))
   (if (null? lst)

If that's not restrictive enough for you, you can use a lambda with a  
throw-away parameter to sequence two actions for side-effects (as  
suggested by others):

((lambda (throw-away) (display "and two"))
  (display "one..."))

Which gives something like...

(define (my-for-each f lst)
   (if (null? lst)
       ((lambda (throw-away)
          (my-for-each f (cdr lst)))
        (f (car lst)))))

For the moment, I can't think of a way to get around the throw-away  
parameter, since scheme (or mzscheme at least) is picky about arity.

Shawn Tice

Posted on the users mailing list.