1.1 The Elements of Programming

Exercise 1.1

1 ]=> 10
;Value: 10

1 ]=> (+ 5 3 4)
;Value: 12

1 ]=> (- 9 1)
;Value: 8

1 ]=> (/ 6 2)
;Value: 3

1 ]=> (+ (* 2 4) (- 4 6))
;Value: 6

1 ]=> (define a 3)
;Value: a

1 ]=> (define b (+ a 1))
;Value: b

1 ]=> (+ a b (* a b))
;Value: 19

1 ]=> (= a b)
;Value: #f

1 ]=> (if (and (> b a) (< b (* a b)))
    b
    a)
;Value: 4

1 ]=> (cond ((= a 4) 6)
      ((= b 4) (+ 6 7 a))
      (else 25))
;Value: 16

1 ]=> (+ 2 (if (> b a) b a))
;Value: 6

1 ]=> (* (cond ((> a b) a)
         ((< a b) b)
         (else -1))
   (+ a 1))
;Value: 16

Exercise 1.2

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

Exercise 1.3

(define (sum-of-the-squares-of-the-larger-two x y z)
  (- (+ (square x) (square y) (square z)) (square (min x y z))))

Exercise 1.4

If b > 0, the procedure returns the result of a + b; else it returns the results of a - b.

Exercise 1.5

Using applicative-order evaluation, the evaluation never terminates, because (p) is defined to itself. Therefore, the interpreter will call procedure p endlessly.

Using normal-order evaluation, the expression evaluates to 0:

(test 0 (p))

((if (= x 0) 0 y) 0 (p))

(if (= 0 0) 0 (p))

(if #t 0 (p))

0

Exercise 1.6

Because new-if is a procedure, it uses applicative-order evaluation. Therefore, the else-clause (sqrt-iter (improve guess x)) will be evaluated unconditionally, which never terminates.

Exercise 1.7

The absolute tolerance of 0.001 is significantly large when computing the square root of a small value. For example, the square root of 0.0001 yields .03230844833048122, with an error over 200% away from the expected value 0.01.

Moreover, for very large numbers, the float precision of the machine is unable to represent small differences between large numbers, and the algorithm never terminates.

The improved good-enough? that works better for small and large numbers:

(define (good-enough? guess x)
  (< (abs (- (improve guess x) guess)) .001))

Exercise 1.8

(define (cube-root-iter guess x)
  (if (good-enough? guess x)
      guess
      (cube-root-iter (improve guess x) x)))

(define (improve guess x)
  (/ (+ (/ x (square guess)) (* 2 guess)) 3))

(define (good-enough? guess x)
  (< (abs (- (improve guess x) guess)) .001))

(define (cube-root x)
  (cube-root-iter 1. x))

Project Versions

Table Of Contents

Previous topic

My SICP Solutions

Next topic

1.2 Procedures and the Process They Generate

This Page