Overview
I would certainly appreciate suggestions of other extra credit activities (preferably via email).
Ignore the zip code problems. Sorry about that!
Lab writeup: Problem 5
Note: and and or stop as soon as they know their result.
(and ... #f .....) stops at the #f.(or ... #t ...) stops at the #t.Generalizing reduce
(define REDUCE-PROC
(lambda (lst)
(if (null? (cdr lst))
(car lst)
(PROC (car lst) (REDUCE-PROC (cdr lst))))))
(define REDUCE
(lambda (proc lst)
(if (null? (cdr lst))
(car lst)
(PROC (car lst) (REDUCE proc (cdr lst))))))
Extending contains-needle? for nested lists
; Using our pattern
(define contains-needle?
(lambda (lst)
(and (not (null? lst))
(or (eq? 'needle (car lst))
(contains-needle? (cdr lst))))))
; Rewritten less elegantly, but perhaps more helpfully
(define contains-needle?
(lambda (lst)
(cond
[(null? lst)
#f]
[(eq? (car lst) 'needle)
#t]
[else
(contains-needle (cdr lst))])))
; Add: Check in nested lists
(define contains-needle?
(lambda (lst)
(cond
[(null? lst)
#f]
[(eq? (car lst) 'needle)
#t]
[(list? (car lst))
(or
(contains-needle (car lst))
(contains-needle (cdr lst)))]
[else
(contains-needle (cdr lst))])))
What do you think about this solution for smallest?
(define smallest
(lambda (lst)
(cond
[(null? (cdr lst))
(car lst)]
[(< (car lst) (smallest (cdr lst)))
(car lst)]
[else
(smallest (cdr lst))])))
We discover that (smallest (range 100)) is really fast and
(smallest (range 30)) is unbearably slow.
> (time (smallest (reverse (range 25))))
cpu time: 968 real time: 966 gc time: 8
0
> (time (smallest (reverse (range 26))))
cpu time: 1908 real time: 1905 gc time: 8
0
> (time (smallest (reverse (range 27))))
cpu time: 3780 real time: 3781 gc time: 8
0
> (time (smallest (reverse (range 28))))
cpu time: 8240 real time: 8240 gc time: 24
0