begriffs

Continuation Passing Style in Haskell

June 3, 2015

Ryan Orendorff presents a tutorial about using continuation passing style in Haskell. He starts with an introduction that looks a lot like how other functional languages do continuations, then refactors the example to use monads. The continuation monad has been called the “mother of all monads” because of its flexibility. See it in action in the video below.

Summary

  • The basics of Continuation Passing Style (CPS)
  • CPS can be made into a monad, and an operator, “call with current continuation”
  • Motivating the style using the calculation of the area of a circle
  • Creating a suspended computation with cpsify
  • Manual chaining of suspended computations is a pain
  • The pattern can be seen as a monad, with cpsify as return and chain as >>=
  • The do notation provides nice sugar for CPS
  • We can create suspended computations, chain them together, and use a type Cont to help prevent mistakes
  • callCC
    • Allows exotic control structures, anything you can imagine: Exceptions, Coroutines, Generators, Iterators
    • An example of an “eject button” that short-circuits computation
  • Despite their promise, continuations are generally confusing and haven’t provided practical control structures