Nothing to Teach

Exercise 1.1

SICP 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.

 110
 2;; 10
 3
 4(+ 5 3 4)
 5;; 12
 6
 7(- 9 1)
 8;; 8
 9
10(/ 6 2)
11;; 3
12
13(+ (* 2 4) (- 4 6))
14;; 6
15
16(define a 3)
17a 
18;; 3
19
20(define b (+ a 1))
21b 
22;; 4
23
24(+ a b (* a b))
25;; 19
26
27(= a b)
28;; #f
29
30(if (and (> b a) (< b (* a b)))
31    b
32    a)
33;; returns value of b
34;; 4
35
36(cond ((= a 4) 6)
37      ((= b 4) (+ 6 7 a))
38      (else 25))
39;; returns 16 because:
40;; a = 3
41;; b = 4
42;; if b equals 4, return 6 + 7 + a
43;; 6 + 7 + 3 = 16
44
45(+ 2 (if (> b a) b a))
46;; this one confused me
47;; because it sounds like it should be:
48;; if b is greater than a, return (b a)
49;; since b (4) is greater than a (3), return 4 3
50;; then sum 2 4 3 = 9
51;; but when I run:
52(if (> b a) b a)
53;; I get:
544
55;; what I realized I was forgetting is that
56;; the if statement is saying:
57;; if b is greater than a, return b, else return a
58;; since b (4) is greater than a (3), return 4
59;; then sum 2 4 = 6
60
61(* (cond ((> a b) a)
62         ((< a b) b)
63         (else -1))
64   (+ a 1))
65;; if a is greater than b, return a
66;; else if a is less than b, return b
67;; else return -1
68;; then add 1 to a and multiply by the result of the
69;; first conditional
70
71;; so in this case:
72;; a is less than b, so return b which is 4
73;; since (+ a 1) is 3 + 1 is 4
74;; 4 * 4 = 16

Soundtrack: The Weight by Weval

Tags: books sicp