[plt-scheme] sicp exercise 2.23
No, don't use "begin"! One of the main points of this exercise is to learn to use side-effects.
Here is my solution and the results of a sample run:
--
(define nil '())
;Value: nil
(define (for-each proc items)
(if (null? items)
nil
(for-each proc (for-each-helper proc items))))
;Value: for-each
(define (for-each-helper proc items)
(if (null? (proc (car items)))
nil
(cdr items)))
;Value: for-each-helper
(for-each (lambda (x) (newline) (display x))
(list 57 321 88))
57
321
88
;Value: ()
--
It's actually quite simple; just use a side-effect in the if-clause. No need for even a "cond". Nobody said a test-clause couldn't be used for a side effect!
Benjamin L. Russell
--- On Wed, 4/30/08, John Clements <clements at brinckerhoff.org> wrote:
> From: John Clements <clements at brinckerhoff.org>
> Subject: Re: [plt-scheme] sicp exercise 2.23
> To: "Jason Wang" <randomtalk at gmail.com>
> Cc: "PLT Scheme List" <plt-scheme at list.cs.brown.edu>
> Date: Wednesday, April 30, 2008, 3:35 AM
> On Apr 28, 2008, at 11:04 PM, Jason Wang wrote:
>
> >
> > However, my problem is that SICP hasn't introduced
> begin yet...
>
> I don't have a copy of SICP handy (I guess I can just
> tear up my
> Schemer Membership Card right now...), but
> "begin" seems to me to be
> the natural choice to express what you want; it's true
> that there are
> other constructs that behave in a begin-like way, and in
> fact you can
> write begin as a function (for a fixed number of arguments)
> quite
> easily, but I would suggest just using 'begin',
> especially as you've
> been through HtDP already.
>
> John
> Clements_________________________________________________
> For list-related administrative tasks:
> http://list.cs.brown.edu/mailman/listinfo/plt-scheme