


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Last time we saw that integers are unnecessary, because they can be implemented using functions. Today we will discuss how returning from a function is also unnecessary, because we can pass in a function that expresses what should happen next. This allows functions to represent the control flow of a program, and the technique is called continuation passing style (CPS). After today’s lecture, you should be able to
1 gcd1 a 0 = a 2 gcd1 a b | a < b = gcd1 b a 3 | otherwise = gcd1 b $ a ‘mod‘ b
gcd 44 12 ⇒ gcd 12 8 ⇒ gcd 8 4 ⇒ gcd 4 0 ⇒ 4 The running time of this function is roughly O(lg a). Now suppose we’d like to take the GCD of an entire list.
1 gcdstar [] = 0 2 gcdstar (x:xs) = gcd x (gcdstar xs)
Question: What will happen if there is a 1 near the beginning of the sequence?
1 bad1 [] = 0 2 bad1 (x:xs) | x == 1 = 1 3 | otherwise = gcd x $ bad1 xs
This stops the computation, but a lot of work has already been done.
1 bad2 [] = 0 2 bad2 (x:xs) | x == 1 = goto 4 3 | otherwise = gcd x $ bad2 xx 4 return 1
Of course, this is nonsense.
1 gcdstar3 xx | all (λ x → not $ x == 1) xx = gcdstar xx 2 | otherwise = 1
1 report x = do print x 2 plusk a b k = k $ a + b
*Main> plusk 20 33 report 53 *Main> plusk 20 33 (\ r -> plusk 10 r report) 63
1 gcdstark xx k = aux xx k 2 where aux [] nk = nk 0 3 aux (x:xs) nk | x == 1 = k 1 4 | otherwise = aux xs (λ res → nk (gcd x res))
(gcdstar ’(44 12 80 6) report) 2 (gcdstar ’(44 12 1 80 6) report) 1
Step 4 A function call not in tail position needs to be built into a new continuation. Be sure your new continuation calls the old one if appropriate!
C[[(op (f arg))]] → f arg (r − > k(C[[op]] r))
1 bar [] = 10 2 bar (x:xs) | x == 0 = bar xs 3 | otherwise = x + foo xs
1 bark [] k = k 10 -- rule 1, 2 2 bark (x:xs) k | x == 0 = foo xs k -- rule 3 3 | otherwise = foo xs (λ r → k (x + r)) -- rule 4