Thus, to ensure the total absence of a function stack, the entire program must be in CPS. CPS in Haskell In this section we will write a function pyth that calculates the hypotenuse using the Pythagorean theorem. A traditional implementation of the pyth function looks like this: pow2 :: Float -> Float pow2 a = a ** 2 add :: Float -> Float -> Float add a b = a + b pyth :: Float -> Float -> Float pyth a b = sqrt (add (pow2 a) (pow2 b)) To transform the traditional function to CPS, we need to change its signature. The function will get another argument of function type, and its return type depends on that function: pow2' :: Float -> (Float -> a) -> a pow2' a cont = cont (a ** 2) add' :: Float -> Float -> (Float -> a) -> a add' a b cont = cont (a + b) -- Types a -> (b -> c) and a -> b -> c are equivalent, so CPS function -- may be viewed as a higher order function sqrt' :: Float -> ((Float -> a) -> a) sqrt' a = \cont -> cont (sqrt a) pyth' :: Float -> Float -> (Float -> a) -> a pyth' a b cont = pow2' a (\a2 -> pow2' b (\b2 -> add' a2 b2 (\anb -> sqrt' anb cont))) First we calculate the square of a in pyth' function and pass a lambda function as a continuation which will accept a square of a as a first argument. And so on until we reach the result of our calculations. To get the result of this function we can pass id function as a final argument which returns the value that was passed to it unchanged: pyth' 3 4 id == 5.0. The mtl library, which is shipped with GHC, has the module Control.Monad.Cont. This module provides the Cont type, which implements Monad and some other useful functions. The following snippet shows the pyth' function using Cont: pow2_m :: Float -> Cont a Float pow2_m a = return (a ** 2) pyth_m :: Float -> Float -> Cont a Float pyth_m a b = do a2 <- pow2_m a b2 <- pow2_m b anb <- cont (add' a2 b2) r <- cont (sqrt' anb) return r Not only has the syntax become cleaner, but this type allows us