- Section 1: Wednesday Oct 17, 18:30
- Section 2: Wednesday Oct 17, 12:30
Homework can submitted via email or printout by deadline.
(define zero '())
(define (zero? n) (null? n))
(define (add1 n) (cons 'a n))
(define (sub1 n) (cdr n))
Restricting yourself to the interface (zero, zero?,
add1, sub1), provide definitions for the following:
(define one (add1 zero))
(define (add a b)
;; insert body here
)
(define (add a b)
(if (zero? b)
a
(add (add1 a) (sub1 b))))
(define (subtract a b)
(if (zero? b)
a
(subtract (sub1 a) (sub1 b))))
(define (increment n) (+ n 1))
(define increment (lambda (n) (+ n 1)))
There is no difference in meaning, just in syntax.
(define (accumulate op init r) (if (null? r) init (op (first r) (accumulate op init (rest r)))))
10
-2
0
(define (product a b) (if (= a 1) b (+ b (product (- a 1) b))))
(define (*list li) (accumulate product 1 li))
(define (list-append l1 l2) (accumulate cons l2 l1))
(define (list-length li) (accumulate (lambda (a b) (+ 1 b)) 0 li))