[plt-scheme] sicp exercise 2.23
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))
On Tue, Apr 29, 2008 at 11:34 AM, Jason Wang <randomtalk at gmail.com> wrote:
> 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))
> 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.
> -----------------
> Using begin, this problem is quite simple, as below:
> (define (for-each fun items)
> (cond [(not (null? items))
> (begin
> (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
>
> Jason
>
> --
> "It's a wonderful world hobbes ol' buddy, let's go explorin'!" -
> Calvin in "Calvin and Hobbes"
> _________________________________________________
> For list-related administrative tasks:
> http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>