SICP programming exercises

Solved exercises in Scheme (Lisp) from 'Structure and Interpretation of Computer Programs' (MIT Press)


Project maintained by attilagk Hosted on GitHub Pages — Theme by mattgraham

Exercise 1.1

Below is a sequence of expressions. What is the result printed by the interpreter in response to each expression? Assume that the sequence is to be evaluated in the order in which it is presented.

10

10

(+ 5 3 4)

12

(- 9 1)

8

(/ 6 2)

3

(+ (* 2 4) (- 4 6))

6

(define a 3)
(define b (+ a 1))
(+ a b (* a b))

19

(= a b)

#f

(if (and (> b a) (< b (* a b)))
    b
    a)

4

(cond ((= a 4) 6)
      ((= b 4) (+ 6 7 a))
      (else 25))

16

(+ 2 (if (> b a) b a))

6

(* (cond ((> a b) a)
         ((< a b) b)
         (else -1))
   (+ a 1))

16

Exercise 1.2

Translate the following expression into prefix form

(/
  ;; enumerator
  (+
    5
    4
    (-
      2
      (-
        3
        (+
          6
          (/ 4 5 ))))
    )
  ;; denominator
  (*
    3
    (- 6 2)
    (- 2 7))
  )

Evaluating the expression yields -37/150. This is because the enumerator evaluates to 74/5 and the denominator to -60. All numerals are specified as integer as if (/ (- 37) 150) had been given. In contrast, the expression (/ (- 37.0) 150) evaluates to 0.24666666666666667.

Exercise 1.3

Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

Prerequisites—as in the book

(define (square x) (* x x))

(define (sum-of-squares x y)
  (+ (square x) (square y)))

A solution

(define (sum-of-sq-two-larger a b c)
  (cond
    ((and (< a b) (< a c)) (sum-of-squares b c))
    ((and (< b a) (< b c)) (sum-of-squares a c))
    (else (sum-of-squares a b))))

Exercise 1.4

Observe that our model of evaluation allows for combinations whose operators are compound expressions. Use this observation to describe the behavior of the following procedure:

The operator is a compound expression that evaluates to either ‘+’ or ‘-‘ depending on the sign of ‘b’, i.e. whether or , respectively.

(define
  ;; the preocedure's syntax
  (a-plus-abs-b ;; procedure name
          a b) ;; formal parameters
  ;; the procedure's body specifies the semantics
  ( ;; the operator is a compound expression that evaluates to either '+' or '-' depending on the sign of 'b'
   (if (> b 0) + -) a b))

Exercise 1.5

Ben Bitdiddle has invented a test to determine whether the interpreter he is faced with is using applicative-order evaluation or normal-order evaluation. He defines the following two procedures:

(define (p) (p))

(define (test x y)
  (if (= x 0)
      0
      y))

Then he evaluates the expression

(test 0 (p))

What behavior will Ben observe with an interpreter that uses applicative-order evaluation? What behavior will he observe with an interpreter that uses normal-order evaluation? Explain your answer. (Assume that the evaluation rule for the special form if is the same whether the interpreter is using normal or applicative order: The predicate expression is evaluated first, and the result determines whether to evaluate the consequent or the alternative expression.)

Evaluating (p) starts an infinitely recurring process since procedure p has been defined recursively without any base case(s). So, under applicative order the evaluation of the expression (test 0 (p)) is never completed because both arguments of test—which include (p)—must be evaluated before evaluation of the body of test. In contrast, under normal order the argument (p) would only be evaluated if the (= x 0) predicate were false. However, this is not the case, so the evaluation of (test 0 (p)) is completed immediately after the 0 consequent is evaluated. Thus, Ben Bitdiddle’s reasoning is correct, (test 0 (p)) does indeed helps distinguish between applicative and normal order evaluation.

Exercise 1.6

Alyssa P. Hacker doesn’t see why if needs to be provided as a special form. “Why can’t I just define it as an ordinary procedure in terms of cond?” she asks. Alyssa’s friend Eva Lu Ator claims this can indeed be done, and she defines a new version of if:

(define (new-if predicate then-clause else-clause)
  (cond (predicate then-clause)
        (else else-clause)))

Eva demonstrates the program for Alyssa:

(new-if (= 2 3) 0 5)
5
(new-if (= 1 1) 0 5)
0

Delighted, Alyssa uses new-if to rewrite the square-root program:

(define (sqrt-iter guess x)
  (new-if (good-enough? guess x)
          guess
          (sqrt-iter (improve guess x)
                     x)))

What happens when Alyssa attempts to use this to compute square roots? Explain.

Infinitely recurring process is started for the same reason as in the case of Ben Bitdiddle’s (test 0 (p)) (Exercise 1.5). So, the shortcoming of new-if is that it is a procedure and hence—under applicative order of evaluation—all of its arguments must be evaluated first even when the evaluation of some of those arguments never completes.

Exercise 1.7

The good-enough? test used in computing square roots will not be very effective for finding the square roots of very small numbers. Also, in real computers, arithmetic operations are almost always performed with limited precision. This makes our test inadequate for very large numbers. Explain these statements, with examples showing how the test fails for small and large numbers. An alternative strategy for implementing good-enough? is to watch how guess changes from one iteration to the next and to stop when the change is a very small fraction of the guess. Design a square-root procedure that uses this kind of end test. Does this work better for small and large numbers?

The original good-enough?

(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.001))

Tests for later comparison with a very small and large number as argument:

-> (sqrt (/ 1.0 900000000000000000000))
0.03125
-> (sqrt 900000000000000000000)
30000000000.0

Clearly, the result is very inaccurate for the very small argument.

The following procedure may be expected to correctly implement the alternative strategy described above in prose.

(define (good-enough? guess x)
  (> 0.001
    (abs (/ (- (improve guess x) guess) guess))))

But for reasons unclear at this moment the new implementation performs worse than the original one:

-> (sqrt (/ 1.0 900000000000000000000))
3.334032674387409e-11
-> (sqrt 900000000000000000000)
30006294069.48668

Exercise 1.8

Newton’s method for cube roots is based on the fact that if y is an approximation to the cube root of x, then a better approximation is given by the value

Use this formula to implement a cube-root procedure analogous to the square-root procedure. (In section 1.3.4 we will see how to implement Newton’s method in general as an abstraction of these square-root and cube-root procedures.)

A set of possible procedures:

;; the main procedure
(define (cubert x) (cubert-iter 1.0 x))
;; auxiliary procedures
;; improving guess
(define (improve-cube guess x)
  (/
    (+
      (/ x (square guess))
      (* 2 guess))
    3))
;; similar implementation to the new 'good-enough?' procedure
(define (good-enough-cube? guess x)
  (> 0.001
    (abs (/ (- (improve-cube guess x) guess) guess))))
;; iteration
(define (cubert-iter guess x)
  (if (good-enough-cube? guess x)
          guess
          (cubert-iter (improve-cube guess x)
                     x)))

Note that good-enough-cube? is similar to new good-enough? (Exercise 1.7) which seems to perform worse than the old good-enough?.

’ ‘