BillHung.Net


powered by FreeFind     sms

CS 61A Lectures Interesting Codes

Lecture 2

(define (opposite w)
(cond ((equal? w 'great) 'terrible)
((equal? w 'terrible) 'great)
((equal? w 'good) 'bad)
((equal? w 'bad) 'good)
((equal? w 'like) 'dislike)
((equal? w 'dislike) 'like)
((equal? w 'love) 'hate)
((equal? w 'hate) 'love)
(else w)))

Lecture 3

(define (every proc sent)
(if (empty? sent)
‘()
(se (proc (first sent))
(every proc (bf sent)))))

(define (compose-with-1+ proc)
(lambda (x) (+ 1 (proc x))))
 > (compose-with-1+ square)
 #[closure...]
 > ((compose-with-1+ (lambda (x) (* 2 x))) 2)
 5
 > ((compose-with-1+ square) 3)
 10

Lecture 6 Exponential

;Recursive way
(define (exp a b)
(if (= b 0)
1
(* a (exp a (- b 1)))))

;Iterative way
(define (exp a b)
(define (helper count result)
(if (= count b)
result
(helper (+ count 1) (* a result))))
(helper 0 1))

;Fast-exponential
(define (fast-exp b n)
(cond ((= n 0) 1)
((even? n) (square (fast-exp b (/ n 2))))
(else (* b (fast-exp b (- n 1))))))

Fibonacci Number
http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2

(define (fib n)
  (cond ((= n 0) 0)
        ((= n 1) 1)
        (else (+ (fib (- n 1))
                 (fib (- n 2))))))
(define (fib n)
  (fib-iter 1 0 n))

(define (fib-iter a b count)
  (if (= count 0)
      b
      (fib-iter (+ a b) a (- count 1))))