Overview

14 Lazy computations, continuations, and the beauty of monadic composition

This chapter explores how deferred execution can make functional code more efficient and expressive. It begins with lazy computations, showing that values should sometimes be wrapped in functions so they are only evaluated if actually needed. Using examples like choosing between two alternatives and providing fallback behavior for optional values, the chapter explains how laziness avoids unnecessary work, especially when computations are expensive or involve I/O. It also emphasizes the practical rule that APIs should accept lazy arguments whenever a function might not use all of its inputs.

The discussion then broadens from plain laziness to computations with effects, especially failure handling through Try. A Try represents a computation that may throw, and a Run operation safely executes it while capturing success or exception in a functional result type. This makes it possible to define safe wrappers around risky operations, such as parsing JSON or creating URIs, without repeating try-catch boilerplate. The chapter shows how such computations can be composed monadically with Bind, allowing multiple potentially failing steps to be chained so that later steps run only if earlier ones succeed, with LINQ query syntax making these compositions more readable.

Finally, the chapter turns to continuations and middleware-style composition, where functions take callbacks and perform work before and after invoking them. It shows how this pattern naturally arises in scenarios like connection management, logging, timing, and transactions, and how nested callbacks can quickly become hard to read. By abstracting the pattern into a middleware monad, the chapter demonstrates how to use Map, Bind, and Run to build flat, composable pipelines that avoid callback hell. The result is a general view of monadic composition as a way to structure complex workflows—whether they involve laziness, failure, or continuation passing—through a disciplined and reusable abstraction.

Definition of Map for Func<T>
A middleware pipeline for accessing the DB
A single middleware function
Bind adds a middleware block to the pipeline.
Map adds a transformation to the pipeline.

Summary

  • Laziness means deferring a computation until its result is needed. It’s especially useful when the result may not be required in the end.
  • Lazy computations can be composed to create more complex computations that can then be triggered as needed.
  • When dealing with an exception-based API, you can use the Try delegate type. The Run function safely executes the code in the Try and returns the result wrapped in an Exceptional.
  • HOFs in the form (T → R) → R (functions that take a callback or continuation) can also be composed monadically, enabling you to use flat LINQ expressions rather than deeply nested callbacks.

FAQ

What is a lazy computation in this chapter’s context?A lazy computation is a function whose execution is deferred until its result is actually needed. Instead of passing a computed value directly, you pass a function such as Func<T> that can produce the value later.
Why would you use laziness instead of eagerly evaluating all arguments?Use laziness when a computation may be expensive or may not be needed at all. This avoids unnecessary work, which is especially useful for costly calculations or I/O operations.
How does the lazy version of Pick avoid wasted computation?By taking Func<T> arguments instead of values, Pick chooses which function to invoke first and only evaluates the selected one. That means only one branch is computed instead of both.
What problem does Option.OrElse solve?OrElse lets you provide a fallback Option if the first one is None. It is commonly used for scenarios like cache lookup with a database fallback.
Why is OrElse(opt, right) sometimes inefficient?Because the fallback argument right is evaluated before OrElse runs, even when opt is already Some. That can cause unnecessary work, such as hitting the database when the cache already has the value.
How does the lazy overload of OrElse fix the cache example?It takes Func<Option<T>> instead of an already computed fallback Option. The fallback is only invoked when the original option is None, so the database is queried only if needed.
What is the purpose of GetOrElse for Option?GetOrElse extracts the value inside an Option, or returns a default if the option is None. There are overloads for both an eager default value and a lazy fallback function.
How can Func<T> be treated as a functor?You can view a Func<T> as containing the potential to produce a T. Its Map operation composes the original function with another function, yielding a new lazy computation.
What does Bind do for Func<T>?Bind chains lazy computations. It evaluates the first function, feeds its result into the next function, and returns a new lazy computation representing the composed work.
What is monadic composition in this chapter?Monadic composition is a way to compose functions that return wrapped values, such as Try<T> or middleware blocks. Instead of ordinary function composition, the composition logic is handled by Bind, which knows how to sequence the computations and deal with the wrapping effect.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C#, Second Edition Functional Programming in C#, Second Edition ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C#, Second Edition Functional Programming in C#, Second Edition ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C#, Second Edition Functional Programming in C#, Second Edition ebook for free