DJ Strouse

the rantings of a baby scientist

DJ Strouse header image 2

Problem Set 2: Procedures, Procedures, Procedures!

July 17th, 2008 · No Comments · Education

2.1.5: Peano Addition

(define plus (lambda (a b)
(if (zero? b) a
(plus (inc a) (dec b)))))

2.2.3: Writing Iterative Procedures

(define slow-mul (lambda (a b) (help a b 0)))
(define (help a b n)
(if (= b 0)
n
(help a (- b 1) (+ a n))))

2.2.4: Writing Fast Procedures

(define fast-mul (lambda (a b)
(cond
((= b 1) a)
((even? b) (fast-mul (double a) (halve b)))
(else (+ a (fast-mul a (- b 1)))))))

2.2.5: Constant Time Sum

(define quick-sum (lambda (n) (* (+ n 1) (/ n 2))))

2.2.5: Fast Expi

(define fast-expi
(lambda (a b) (help a b 1)))
(define (help a b n)
(cond ((= b 1) (* n a))
((even? b) (help (* a a) (/ b 2) n))
(else (help a (- b 1) (* a n)))))

2.3.1: If as a Special Form

(really-big-hairy-slow-procedure (if (= a 0) 3 4))

*Note: I found the wording of this problem super confusing but basically they’re asking you to rewrite the procedure with only one reference to really-big-hairy-procedure and one reference to ‘if’ (something that would be smart if ‘if’ were not a special form and instead evaluated every expression in its environment).

2.3.4: Mystery

(define clarity (lambda (a b)
(if (> a b)
0
(+ a (clarity (+ a 1) b)))))

Tags:

No Comments so far ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment