[plt-scheme] sicp exercise 2.23

From: Jason Wang (randomtalk at gmail.com)
Date: Tue Apr 29 16:25:56 EDT 2008

On Tue, Apr 29, 2008 at 2:11 AM, Veer <diggerrrrr at gmail.com> wrote:
> I have read up to chapter 4 of htdp , so this is how i will do it at first try
>
>  ;;for-each1
>
>  ;;for-each1 : (X -> Y) (listof X) -> true
>  ;;to apply a (f X) on items of a-list , on success returns true
>  (define (for-each1 f a-lst)
>   (cond
>     [(empty? a-lst) true]
>     [else (and (always-true (f (first a-lst))) (for-each1 f (rest a-lst)))]))
>
>  ;;always-true : X -> true
>  ;;to produce to true for any item
>  (define (always-true item)
>   true)
>
>  ;;print-item : X -> X
>  ;;to print a-item
>  (define (print-item a-item)
>   a-item)
>
>  (for-each1 print-item (list 1 2 3))

Sorry, i didn't know how i managed to miss your post. It is in fact a
very nice solution, but i don't feel good about the extra helper
function always-true. I think the later solution by Evgeny perhaps is
better, as reproduced here:
(define (for-each proc items)
  (if (null? items)
       #t
       (if (proc (car items))
           (for-each proc (cdr items))
           (for-each proc (cdr items)))))

However, i think Shawn's solution is the best in light of the book and
what has been learnt so far. It seems the simplest.

On Tue, Apr 29, 2008 at 1:50 PM, Shawn Tice <0x6d65 at gmail.com> wrote:
> 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)
>   (newline)
>   (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)
>       #t
>       (side-effect-and-continue)))
>
>  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)
>       #t
>       ((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.

Thanks to everyone who have contributed to my question :D

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


Posted on the users mailing list.