Scheme - 0-01
Scheme - 0-01
Programming in Scheme
Geoff Coulson
Department of Computing, Lancaster
University
[email protected]
core material
unit 1: introduction to Scheme: objects and lists
unit 2: introduction to Scheme: lists and recursion
unit 3: more built-in Scheme procedures
applying the core material
unit 4: search
unit 5: more on search
(5 units in 6 lecture slots allows for some
slippage)
=
power2(x)
non-recursive case
if x is 0 then return 1
else
return 2 * (power2 with argument x-1)
recursive case
n.b.
(the first recursive call on a one-symbol list leads to the
symbol? case)
the second recursive call on a one-symbol list leads to
the null? case)
Geoff Coulson, Lancaster University 2/1/07 39
Append: another example with
multiple simple cases
the problem: concatenate two lists
(append (a b c) (d e)) returns (a b c d e)
(append (a b c) ()) returns (a b c)
(append (a (b c)) (d e)) returns (a (b c) d e)
the solution
(define (append l1 l2)
(cond ((null? l1) l2)
((symbol? l1) (cons l1 l2))
(else (append (rdc l1)
(cons (rac l1) l2)))))
rac
solution:
(define (flatten s)
(cond ((null? s) ())
((symbol? s) (list s))
(else (append (flatten (car s))
(flatten (cdr s))))))
3
Geoff Coulson, Lancaster University 2/1/07 51
New version with map/ apply
> (symbol-count2 '((a b) c))
1. Trace: (SYMBOL-COUNT2 '((A B) C))
2. Trace: (SYMBOL-COUNT2 '(A B))
3. Trace: (SYMBOL-COUNT2 'A)
3. Trace: SYMBOL-COUNT2 ==> 1
3. Trace: (SYMBOL-COUNT2 'B)
3. Trace: SYMBOL-COUNT2 ==> 1
2. Trace: SYMBOL-COUNT2 ==> 2
2. Trace: (SYMBOL-COUNT2 'C)
2. Trace: SYMBOL-COUNT2 ==> 1
1. Trace: SYMBOL-COUNT2 ==> 3
3
note that there is significantly less recursion => faster
w
Geoff Coulson, Lancaster University 2/1/07 61
Search strategy 2: breadth first search
movement is level by level: s
at each state examine all the
children of that state; if we t
fail to find a finish state j
among these, move down to u v
one of the children and k x
proceed from there y z
r
i.e. the links one level down
are fully examined before we w
go down to the next level
y z
r
w
Geoff Coulson, Lancaster University 2/1/07 63
Depth first search in a nested list (tree)
basic dfs is in a nested list is trivial!
(define (search finish-state tree)
(cond ((equal? finish-state tree) #t)
((symbol? tree) #f)
(else (or (search finish-state (car tree))
(search finish-state (cdr tree))))))
but this approach has severe limitations
it only works on trees, not graphs
it assumes the tree is already available (i.e., pre-computed)
it only returns #t or #f; it doesnt remember the route it took to get to
the finish
we cant easily extend it to breadth first search and other strategies
so, we will take a more general approach...
(define (dfs s f)
(define (dfs1 queue finish)
(cond ((null? queue) #f)
((equal? (car queue) finish) #t)
(else (dfs1 (append (expand (car queue))
(cdr queue))
finish))))
(dfs1 (list s) f))