Tuesday, March 27, 2012

3.7



(define fact (lambda (n) (if (= n 0) 1 (* n (fact (- n 1))))))

(define (bee n k) (/ (fact n) (* (fact ( - n k)) (fact k))))

(define (binn n k) (if (cond [(= k 0) 1] [(= n k) 1])
                   (+ (bee (- n 1) (- k 1)) (bee (- n 1) k))))

3.5



a.) The factorial function is referentially transparent because it is a function that is only produces one and only one output based on the input.  Unless you do not know what the input will be or there are multiple different inputs;, therefore making the factorial function non referentially transparent.

b.) A function which waits for a key to be pressed then returns pressed key is not referentially transparent because you do know what will be pressed, so using just a value would not be logical.

c.) A function that counts the number of times it is called cannot be a referentially transparent function because it needs to run in order to see what the value is it will output.  

4.17

gcd(U,V,W) :- not(V=0), R is U mod V, !, gcd(V,R,W)
This can be viewed as being tail recursive because it calls itself and will stop once R is U mod V because of the cut.  Tail recursion is when a function calls itself, this is what is occuring in this clause.

4.1

 P Q  P->Q
 T  T   T
 T  F   F
 F  T   T
 F  F   T


nP Q OR
T  T  T
T  F  F
F  T  T
F  F  F

3.8



A) (define (count l) (if (null? l)0 ( + 1 (count (cdr l)))))

B) (define (findmax l) (if (null? (cdr l)) (car l)
     (if (> (car l) (findmax (cdr l)))(car l)
     (findmax (cdr l)))))

C) (define (readnums) (let ((x (read))) (if (= x 0) '() (cons x (readnums)))))

D) (define (findmax l) (if (null? (cdr l)) (car l)
     (if (> (car l) (findmax (cdr l)))(car l)
     (findmax (cdr l)))))

     (define (findmin l) (if (null? (cdr l)) (car l)
     (if (< (car l) (findmin (cdr l))) (car l) (findmin (cdr l)))))

     (define (readnums) (let ((x (read)))
     (if (= x 0) '() (cons x (readnums)))))

    (define (minmax l) (define x l) (cons (findmin x) (list (findmax x))))
    /* Prints out the Min then Max into new list */

E) Quick Sort Scheme

F) Merge Sort Scheme

G) Haskell
pythriple n = [(x,y,z) | x <- [1..n], y <- [x..n], z <- [y..n], x^2 + y^2 == z^2]

Scheme SRFI-42
(define (pythriple n) (list-ec (:range x 1 n) (:range y x n) (:range z y n) (if (= (* z z) (+ (* x x) (* y y))) (list x y z))))
H) 8x 
(define square (lambda (x) (* x x))) 
(define twice (lambda (f) (lambda (x) (f (f x)))))

I)  (define ((inc_n n) x) 
        (cond [(> x 0) ((inc_n (+ n 1)) (- x 1))]
                  [else n]))