What does this code do?
def foo(a):
res = ""
if a > 100:
res = bar(qux(a))
else:
res = baz(a % 7)
print(res)
def bar(b):
return b*9
def qux(c):
return c % 10
def baz(d):
return d*19
Running a program
An "if statement
Calling a subroutine
Entering the subroutine. Allocate a stack frame to "remember where we were"
Return the value & pop the stack frame
Its what happens next
What happens if you take away function return???
Here comes the headache
def foo(a, next):
step = lambda b : bar(a, b, next)
baz(step)
def bar(a, b, next):
next(a + b)
def baz(next):
next(42)
Explicitly declaring what happens next is equivalent to GOTO!
Why would you want this??
Implement new control flows
A continuation takes the form of (a -> r) -> r. This is a Functor, Applicative, and Monad
type Cont r a = (a -> r) -> rrunCont :: Cont r a -> r) -> (a -> r) -> rcallCC :: ((a -> Cont r b) -> Cont r a) -> Cont r a
fun :: Int -> String
fun n = (`runCont` id) $ do
str <- callCC $ \exit1 -> do
when (n < 10) (exit1 (show n))
let ns = map digitToInt (show (n `div` 2))
n' <- callCC $ \exit2 -> do
when ((length ns) < 3) (exit2 (length ns))
when ((length ns) < 5) (exit2 n)
when ((length ns) < 7) $ do
let ns' = map intToDigit (reverse ns)
exit1 (dropWhile (=='0') ns')
return $ sum ns
return $ "(ns = " ++ (show ns) ++ ") " ++ (show n')
return $ "Answer: " ++ str