learning-sicp

My embarrassing half assed SICP run.
git clone https://kaka.farm/~git/learning-sicp
Log | Files | Refs

exercise-22.scm (1671B)


      1 ;; Exercise 2.22
      2 
      3 (define (exercise-2.22)
      4   (define (square-list-1 items)
      5     ;; answer is build by consing the first element of items onto the input nil
      6     ;; (item-1 . nil) then the second onto (item-1 . nil), (item-2 . (item-1 . nil))
      7     ;; and the third (item-3 . (item-2 . (item-1 . nil))).
      8     ;; In other words, you start by consing the first item onto the end of answer
      9     ;; and you end by consing the last item of items onto the start of answer,
     10     ;; building the cons onion inside out.
     11     (define (iter things answer)
     12       (if (null? things)
     13           answer
     14           (iter (cdr things)
     15                 (cons (* (car things)
     16                          (car things))
     17                       answer))))
     18     (iter items '()))
     19 
     20   (define (square-list-2 items)
     21     ;; In the second attempt you cons the answer to the first item (nil . item-1)
     22     ;; then the answer onto the second item ((nil . item-1) item-2) and so on
     23     ;; until you cons the answer onto the last item (... . item-n) which is the
     24     ;; same as the first attempt, but instead of the accepted
     25     ;; items-go-on-car-rest-of-list-goes-on-cdr, you have items-go-on-cdr-rest-of-list-goes-on-car.
     26     ;; ((((nil . item-1) . item-2) . item-3) . item-4).
     27     (define (iter things answer)
     28       (if (null? things)
     29           answer
     30           (iter (cdr things)
     31                 (cons answer
     32                       (* (car things)
     33                          (car things))))))
     34     (iter items '()))
     35 
     36   (test-begin "2.22")
     37   (test-equal
     38       '(16 9 4 1)
     39     (square-list-1 '(1 2 3 4)))
     40   (test-equal
     41       '((((() . 1) . 4) . 9) . 16)
     42     (square-list-2 '(1 2 3 4)))
     43   (test-end "2.22"))
     44 
     45 (exercise-2.22)