Saturday, May 30, 2009

Ex-1.15 - todo

a: 5
b: todo

Ex-1.14 - todo

todo

Ex-1.13

passed

Ex-1.12

;; Find Pascal element
;; row = row number in the pascal triangle,
;; row >= 1
;; elt = elt'th element of the row,
;; 1 <= elt <= row
(define (pascal row elt)
(if (or (= elt 1) (= elt row)) 1
(+ (pascal (- row 1) (- elt 1))
(pascal (- row 1) elt))))

Ex-1.11

;;
;; foo(n) = 0 if n=0
;; = 1 if n=1
;; = 2 if n=2
;; = foo(n-1)+2foo(n-2)+3foo(n-3)
;;

;;recursive definition
(define (foo n)
(cond
((= n 0) 0)
((= n 1) 1)
((= n 2) 2)
(else
(+ (foo (- n 1))
(* 2 (foo (- n 2)))
(* 3 (foo (- n 3)))))))

;;iterative definition
(define (foo n)
(foo-iter 2 1 0 n))
(define (foo-iter a b c count)
(cond
((= count 0) c)
(else
(foo-iter
(+ a (* 2 b) (* 3 c)) a b (- count 1)))))

The general technique to convert recursive->iterative is to somehow find an invariant assertion that remains true from one iteration to another and wind-up the state in arguments.
As in above iterative definition state is in a, b & c and invariant assertion is that c, b & a are foo of 3 consecutive numbers.

Ex-1.10

passed.

Ex-1.9

First Version:
Its not tail-recursive, process generated is recursive.
(+ 4 5)
(inc (+ 3 5))
(inc (inc (+ 2 5)))
(inc (inc (inc (+ 1 5))))
(inc (inc (inc (inc (+ 0 5)))))
(inc (inc (inc (inc 5))))
(inc (inc (inc 6)))
(inc (inc 7))
(inc 8)
9

Second Version:
Its tail-recursive, process generated is iterative.
(+ 4 5)
(+ 3 6)
(+ 2 7)
(+ 1 8)
(+ 0 9)
9


Tail-Recursive Procedure: If there is only one recursive call in the procedure and that is THE LAST call in the procedure body.

Ex-1.8

(define (cubert x)
(cubert-iter 1.0 x))

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

(define (good-enough? guess x)
(< (abs (- (cube guess) x)) 0.001))

(define (cube x) (* x x x))

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

The thing to notice is that due to appropriate use of procedural abstraction only improve(and good-enough a little bit) is changed between sqrt and cubert.

Ex-1.7

passed.

Ex-1.6

That'll fall inside an infinite recursion.

new-if is a procedure, due to applicative-order evaluation behavior, interpreter will try to evaluate all the args passed to new-if(before starting to evaluate its body) which in this case include call to sqrt-iter again.

Ex-1.5

applicative-order behavior:
It'll try to evaluate the args passed to test, which will lead it to evaluate (p) and that will put it into a infinite recursion.

normal-order behavior:
In this case test body will start evaluating without evaluating the args(until they're needed) , will return 0 and exit.