SICP. Exercises 2.21 and 2.23
2023-04-05 Wed

Here are the solutions to exercises 2.21 and 2.23 which should have been included in the previous post (I'm skipping 2.22).

Exercise 2.21

Exercise:

The procedure square-list takes a list of numbers as argument and returns a list of the squares of those numbers.

(square-list (list 1 2 3 4))
(1 4 9 16)

Here are two different definitions of square-list. Complete both of them by filling in the missing expressions:

(define (square-list items) (if (null? items) nil (cons ⟨??⟩ ⟨??⟩)))

(define (square-list items) (map ⟨??⟩ ⟨??⟩))

Answer:

(define (square-list items)
  (if (null? items)
      nil
      (cons (square (car items))
            (square-list (cdr items)))))

(define (square-list items)
  (map square items))

Exercise 2.23

Exercise:

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.

Answer:

(define (for-each proc items)
  (if (null? items)
      true
      (and (proc (car items))
           (for-each proc (cdr items)))))

Send me an email for comments.

Created with Emacs 28.2 (Org mode 9.5.5)