cosmin/sicp-scheme

1 parent 9b44fd8 commit 45727cc9145122c3cc27fc87f0759bd08f8e0863 committed Feb 1, 2010
Showing with 64 additions and 0 deletions.
1. +5 −0 exercise-1-04.ss
2. +14 −0 exercise-1-05.ss
3. +22 −0 exercise-1-06.ss
4. +23 −0 exercise-1-09.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
 @@ -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
 @@ -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
 @@ -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