Overview
I would certainly appreciate suggestions of other extra credit activities (preferably via email).
A few of us traded names this morning. Will that effect the quiz?
For the quiz, you must use the name you have been using for the earlier part of the semester.
We’ve been talking about recursion and have a basic model of recursion.
(define proc
(lambda (lst)
(if (null? lst)
base-case
(combine (car lst) (proc (cdr lst))))))
(define product
(lambda (lst)
(if (null? lst)
1
(* (car lst) (product (cdr lst))))))
(define product
(lambda (lst)
(if (singleton? lst)
(car lst)
(* (car lst) (product (cdr lst))))))
Detour: What’s going on with nested tick marks (nested quotes)?
'thing is a shorthand for (quote thing)(quote thing) is a keyword that says “take this thing as is, without
evaluating it”(quote 5) is 5(quote sam) is 'sam(quote '(1 2 3)) is a three-element list> (quote 5)
5
> (quote sam)
'sam
> (quote (1 2 3))
'(1 2 3)
> (quote (1 (+ 2 3) 4))
'(1 (+ 2 3) 4)
> (list? (list-ref (quote (1 (+ 2 3) 4)) 1))
#t
> (list? (list-ref (quote (1 (quote a) 2)) 1))
#t
> (list-ref (quote (1 (quote a) 2)) 1)
''a
> '(quote a)
''a
> (list-ref '(1 'a 2) 1)
''a
> (quote (and a))
'(and a)
> (quote (quote a))
''a
> (list? (quote (quote a)))
#t
The moral? Don’t nest tick marks. It makes everbody’s brain hurt.
</detour>
Back to recursion.
Observation: Sometimes we want to keep track of extra values while recursing. E.g., reversing a list.
remaining so-far
--------- ------
'(a b c) '()
cdr cons
'(b c) '(a)
cdr cons
'(c) '(b a)
cdr cons
'() '(c b a)
Let’s try expressing that in Scheme. Is this correct?
(define rev
(lambda (lst)
(if (null? lst)
null
(cons (car lst) (rev (cdr lst))))))
This does not work. In fact, our model of thinking through the problem suggests we need two parameters, rather than one. But reverse should only have one parameter.
(define rev
(lambda (lst)
(rev-kernel lst '())))
(define rev-kernel
(lambda (remaining reversed-so-far)
(if (null? remaining)
reversed-so-far
(rev-kernel (cdr remaining)
(cons (car remaining) reversed-so-far)))))
It can be helpful to put in a call to display.
(define rev
(lambda (lst)
(rev-kernel lst '())))
(define rev-kernel
(lambda (remaining reversed-so-far)
(display (list 'kernel remaining reversed-so-far)) (newline)
(if (null? remaining)
reversed-so-far
(rev-kernel (cdr remaining)
(cons (car remaining) reversed-so-far)))))
No writeup! It’s break.