Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

added answers for 1.4 - 1.6 and 1.9

  • Loading branch information...
commit 45727cc9145122c3cc27fc87f0759bd08f8e0863 1 parent 9b44fd8
@cosmin authored
View
5 exercise-1-04.ss
@@ -0,0 +1,5 @@
+(define (a-plus-abs-b a b)
+ ((if (> b 0) + -) a b))
+
+; if b is greater than 0 then the function will compute a + b
+; otherwise it will compute a - b
View
14 exercise-1-05.ss
@@ -0,0 +1,14 @@
+(define (p) (p))
+(define (test x y)
+ (if (= x 0)
+ 0
+ y))
+
+
+(test 0 (p))
+
+; if the interpreter is using applicative ordering then before test is called
+; p will be called, and p will cause infinite recursion
+;
+; if the interpreter is using normal evaluation order then p will not be
+; evaluated when calling (test 0 (p)) because test will return 0
View
22 exercise-1-06.ss
@@ -0,0 +1,22 @@
+(define (new-if predicate then-clause else-clause)
+ (cond (predicate then-clause)
+ (else else-clause)))
+
+(define (improve guess x)
+ (average guess (/ x guess)))
+
+(define (average x y) (/ (+ x y) 2 ))
+
+(define (good-enough? old-guess guess)
+ (< (abs (- old-guess guess)) (* old-guess 0.001)))
+
+(define (sqrt-iter guess x)
+ (new-if (good-enough? guess x)
+ guess
+ (sqrt-iter (improve guess x)
+ x)))
+
+(sqrt-iter 1 10)
+
+; sqrt-iter will recurse infinitely because sqrt-iter will be evaluated before
+; calling new-if since new-if is a function and follows applicative order eval
View
23 exercise-1-09.ss
@@ -0,0 +1,23 @@
+(define (inc x)
+ (+ x 1))
+
+(define (dec x)
+ (- x 1))
+
+;
+
+(define (plus a b)
+ (if (= a 0)
+ b
+ (inc (plus (dec a) b))))
+
+; (plus 2 2) => (inc (inc 2)) => 4
+; this is a linear recursive process
+
+(define (plus* a b)
+ (if (= a 0)
+ b
+ (plus* (dec a) (inc b))))
+
+; (plus* 2 2) => (plus* 1 3) => (plus* 0 4) => 4
+; this is an iterative process
Please sign in to comment.
Something went wrong with that request. Please try again.