Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

added answers for 1.4 - 1.6 and 1.9

  • Loading branch information...
commit 45727cc9145122c3cc27fc87f0759bd08f8e0863 1 parent 9b44fd8
Cosmin Stejerean authored
5 exercise-1-04.ss
... ... @@ -0,0 +1,5 @@
  1 +(define (a-plus-abs-b a b)
  2 + ((if (> b 0) + -) a b))
  3 +
  4 +; if b is greater than 0 then the function will compute a + b
  5 +; otherwise it will compute a - b
14 exercise-1-05.ss
... ... @@ -0,0 +1,14 @@
  1 +(define (p) (p))
  2 +(define (test x y)
  3 + (if (= x 0)
  4 + 0
  5 + y))
  6 +
  7 +
  8 +(test 0 (p))
  9 +
  10 +; if the interpreter is using applicative ordering then before test is called
  11 +; p will be called, and p will cause infinite recursion
  12 +;
  13 +; if the interpreter is using normal evaluation order then p will not be
  14 +; evaluated when calling (test 0 (p)) because test will return 0
22 exercise-1-06.ss
... ... @@ -0,0 +1,22 @@
  1 +(define (new-if predicate then-clause else-clause)
  2 + (cond (predicate then-clause)
  3 + (else else-clause)))
  4 +
  5 +(define (improve guess x)
  6 + (average guess (/ x guess)))
  7 +
  8 +(define (average x y) (/ (+ x y) 2 ))
  9 +
  10 +(define (good-enough? old-guess guess)
  11 + (< (abs (- old-guess guess)) (* old-guess 0.001)))
  12 +
  13 +(define (sqrt-iter guess x)
  14 + (new-if (good-enough? guess x)
  15 + guess
  16 + (sqrt-iter (improve guess x)
  17 + x)))
  18 +
  19 +(sqrt-iter 1 10)
  20 +
  21 +; sqrt-iter will recurse infinitely because sqrt-iter will be evaluated before
  22 +; calling new-if since new-if is a function and follows applicative order eval
23 exercise-1-09.ss
... ... @@ -0,0 +1,23 @@
  1 +(define (inc x)
  2 + (+ x 1))
  3 +
  4 +(define (dec x)
  5 + (- x 1))
  6 +
  7 +;
  8 +
  9 +(define (plus a b)
  10 + (if (= a 0)
  11 + b
  12 + (inc (plus (dec a) b))))
  13 +
  14 +; (plus 2 2) => (inc (inc 2)) => 4
  15 +; this is a linear recursive process
  16 +
  17 +(define (plus* a b)
  18 + (if (= a 0)
  19 + b
  20 + (plus* (dec a) (inc b))))
  21 +
  22 +; (plus* 2 2) => (plus* 1 3) => (plus* 0 4) => 4
  23 +; this is an iterative process

0 comments on commit 45727cc

Please sign in to comment.
Something went wrong with that request. Please try again.