continuation-passing style (CPS) does: makes control flow explicit via callbacks

Why can't we just call functions directly and let them handle everything?

Image: kees torn, CC BY-SA 2.0, via Wikimedia Commons

continuation-passing style (CPS) does: makes control flow explicit via callbacks

Why can't we just call functions directly and let them handle everything?

Imagine you're cooking a meal and need to prepare several dishes at once. You can't just start cooking without knowing when each dish is done and how to serve them.

In cooking, you'd need to keep track of each dish's progress and when to serve them. CPS is like cooking with a recipe that tells you exactly when to finish each dish and serve it, making sure everything comes out perfectly timed.

Example

You have a chicken (C), potatoes (P), and a salad (S). In direct style, you start cooking the chicken and potatoes together. In CPS, you cook the chicken and say, "When you're done, serve the chicken." Then you cook the potatoes and say, "When the potatoes are done, serve them." Finally, you prepare the salad and say, "When the salad is ready, serve it."

Remember this

CPS makes sure each step in a process happens at the right time, like a perfectly timed meal.

Related concepts

Swipe through 100 ML concepts daily

Open Pocket Polymath