Programming Paradigms CSI2120: Jochen Lang EECS, University of Ottawa Canada
Programming Paradigms CSI2120: Jochen Lang EECS, University of Ottawa Canada
Programming Paradigms CSI2120: Jochen Lang EECS, University of Ottawa Canada
Paradigms
CSI2120
Jochen Lang
EECS, University of Ottawa
Canada
Scheme: Functional Programming
• Tree representations
• Binary search trees
• Lazy evaluations
• Examples
– Towers of Hanoi
– Tic Tac Toe
a (a b (c d e))
or
(a (b () ()) (c (d () ()) (e () ()))
b c
or
(a b.(c d.e))
d e
(define removemax-BST
(lambda (t)
(cond
((null? (caddr t)) (cons (cadr t) (car t)))
(else
(let ((r (removemax-BST (caddr t))))
(cons (list (car t) (cadr t) (car r)) (cdr r))
))
)))
=> removemax-BST
(removemax-BST '(73 (31 (5 () ()) ()) (101 (83 ()
(97 () ())) ())))
=> ((73 (31 (5 () ()) ()) (83 () (97 () ()))) . 101)
(define delete-BST
(lambda (x t)
(if
(not (tree? t))
(list 'not-a-tree t)
(delete x t)
)))
=> delete-BST
(delete-BST 101 '(73 (31 (5 () ()) ()) (101 (83
() (97 () ())) ())))
=> (73 (31 (5 () ()) ()) (83 () (97 () ())))
• Member of a Series
– In some cases, it is possible to obtain a result without having
to calculate all the elements of a series.
• Define a series
(define (series n1 n2 N)
(begin
(if (zero? N) ()
(cons (+ n1 n2)
(series n2 (+ n1 n2) (- N 1))))))
=> series
(series 0 1 10)
=> (1 2 3 5 8 13 21 34 55 89)
(define (series n1 n2 N)
(if (zero? N) ()
(cons (+ n1 n2)
(delay (series n2 (+ n1 n2) (- N 1))))))
=> series
(series 0 1 200)
=> (1 . #[promise 1])
• Get a promise which we can force
(cons (car(series 0 1 200))
(force (cdr(series 0 1 200))))
=> (1 2 . #[promise 2])
(define (in-seq x L)
(let ((tmp (car L)))
(cond ((null? L) ())
((< x tmp) ())
((= x tmp) x)
(#t (in-seq x (force (cdr L)))))))
=> in-seq
(in-seq 15 (series 0 1 200))
=> ()
• The series evaluation will only have to be forced until a
value greater or equal the number x is reached.
(hanoi 3)
move 1 --> 3
move 1 --> 2
move 3 --> 2
move 1 --> 3
move 2 --> 1
move 2 --> 3
move 1 --> 3
=>
1 2 3 X
4 5 6
7 8 9 O
X
X X
O O
• Tree representations
• Binary search trees
• Lazy evaluations
• Examples
– Towers of Hanoi
– Tic Tac Toe