Advanced Functional Programming: Continuations
Advanced Functional Programming: Continuations
Advanced Functional
Programming
Continuations
Continuation passing style
Continuation monad
Throw and catch
Callcc
Lecture 11
Tim Sheard
Continuations
Lecture 11
Tim Sheard
Lists in CPS
Lecture 11
Tim Sheard
Lecture 11
Remember this
pattern
Tim Sheard
Is it efficient?
tree1 = Fork (Fork (Tip 1) (Tip 2))
(Fork (Tip 3) (Tip 4))
double 0 x = x
double n x = double (n-1) (Fork x x)
Lecture 11
Tim Sheard
Test results
Main> :set +s
Main> ex1
65536
(1179828 reductions, 2359677 cells, 10 garbage collections)
Main> ex2
65536
(2425002 reductions, 5505325 cells, 34 garbage collections)
Lecture 11
Tim Sheard
Advantages of CPS
(prefix p xs)
that
Tim Sheard
Code
Lecture 11
Tim Sheard
Prefix in CPS
Lecture 11
Tim Sheard
Style
prefixC p [] k = Nothing
prefixC p (x:xs) k =
if p x
then prefixC p xs (cons x k)
else k (Just [])
where cons x k (Just xs) = k (Just(x:xs))
cons x k Nothing =
error "This case is never called
prefixC p [] k = Nothing
prefixC p (x:xs) k =
if p x
then prefixC p xs (\ (Just xs) ->
k(Just(x:xs)))
else k (Just [])
Lecture 11
Tim Sheard
10
Lecture 11
Tim Sheard
11
Lecture 11
Tim Sheard
12
Pattern Matching
Lecture 11
Tim Sheard
13
Match function
Lecture 11
Tim Sheard
14
Example tests
t1
p1
p2
p3
p4
=
=
=
=
=
Main> match p1 t1
Just [("x",(5,6)),("y",7)]
Main> match p2 t1
Nothing
Main> match p3 t1
Just [("x",5),("y",6)]
Main> match p4 t1
Just [("x",5),("y",6)]
Lecture 11
Tim Sheard
15
Match in CPS
matchC :: Pat -> Term -> (Sub -> Maybe ans) -> Maybe ans
Tim Sheard
16
Two continuations
Lecture 11
Tim Sheard
17
t1
p1
p2
p3
p4
=
=
=
=
=
Tests
ex9 = matchC2 p4 t1 id id
Main> ex10
Just [("x",5),("y",6)]
Lecture 11
Tim Sheard
18
Fixing matchC
matchK :: Pat -> Term -> (Sub -> Maybe ans) -> Maybe ans
Tim Sheard
19
Lecture 11
Tim Sheard
20
Tim Sheard
21
Interpreters in CPS
data Exp =
|
|
|
|
Var String
Lam String Exp
App Exp Exp
Num Int
Op (Int -> Int -> Int) Exp Exp
plus x y = Op (+) x y
times x y = Op (*) x y
minus x y = Op (-) x y
extend :: Eq a => (a -> b) -> b -> a -> a -> b
Tim Sheard
22
Eval in CPS
Lecture 11
Tim Sheard
23
type C x = Cont U x
data U = Fun2 (U -> C U)
| N2 Int
eval2
eval2
eval2
do
Lecture 11
Tim Sheard
24
data Exp =
|
|
|
|
|
|
Var String
Lam String Exp
App Exp Exp
Num Int
Op (Int -> Int -> Int) Exp Exp
Raise Exp
Handle Exp Exp
type C3 x = Cont W x
data W = Fun3 (W -> C3 W)
| N3 Int
| Err W
Lecture 11
Tim Sheard
25
eval3
eval3
eval3
do
Tim Sheard
26