Overview

15 Stateful programs and stateful computations

This chapter explains how functional programming can model programs that must keep track of past information without relying on hidden mutation. A program is stateful when its behavior depends on earlier inputs or events, and the key idea is to make that state explicit by passing it into functions and returning an updated state alongside results. Using a currency-rate lookup example, the text shows how a cache can be represented as immutable data, how recursive control flow can thread that cache through each call, and how the same pattern can be rewritten as a loop when recursion would be impractical in C#.

The chapter then improves the stateful lookup by separating pure logic from I/O and by adding error handling in a functional style. By injecting the rate-fetching function as an argument, the lookup becomes much easier to test, and wrapping the operation in a Try type allows failures to be handled gracefully without exceptions scattered throughout the code. The broader lesson is that functional stateful programs gain clarity from richer function signatures: they make dependencies, state transitions, and possible errors explicit rather than relying on global variables or imperative side effects.

After that, the chapter shifts to a more general view of stateful computations, treating them as functions that take a state and return both a value and a new state. Random number generation is used to illustrate this idea, with a generator type that carries a seed forward so that complex random values can be built from simpler ones. The same pattern is then generalized with Map, Bind, and LINQ to compose computations without manually threading state, culminating in a tree-numbering example that shows how this technique can simplify more complex traversals and forms the basis for later uses such as parsers and simulations.

Keeping a cache of previously retrieved rates
Using the NextInt generator to generate a Boolean
Definition of Bind for Generator<T>
Numbering each element in a tree

Summary

  • When writing stateful programs, you can avoid changing state as a side effect by always passing the state explicitly as part of your functions' input and output.
  • Stateful computations are functions in the form S → (T, S). They take some state and return a value as well as an updated state.
  • Stateful computations can be composed monadically to reduce the syntactic burden of passing the state from one computation to the next.

FAQ

What is a stateful program?A stateful program is one whose behavior changes depending on past inputs or events. In other words, the program remembers something about previous interactions, and that memory affects future behavior.
How can a functional program manage state without mutating global variables?By passing the current state into functions as an argument and returning the updated state as part of the result. This makes state explicit while avoiding mutation of global variables.
Why is the FX rate lookup example considered stateful?It becomes stateful when it keeps a cache of previously retrieved exchange rates. The cache changes how the program behaves because repeated requests can return cached values instead of making new HTTP calls.
What type is used to represent the cache of FX rates?The cache is represented as an immutable dictionary, aliased as Rates. Conceptually, it maps a currency pair string to a decimal exchange rate.
What is the difference between the stateless and stateful versions of GetRate?The stateless version takes only a currency pair and returns a rate. The stateful version also takes the current cache state and returns both the rate and the updated cache.
How does the program avoid mutation while still updating the cache?Instead of modifying the existing cache, it creates and returns a new immutable dictionary with the new rate added. The caller then passes that new state to the next step.
Why does the chapter say that the stateful program is still stateful even without global variables?Because the program still keeps state in memory, and that state affects subsequent operations. Statefulness does not require global variables; it only requires that past actions influence future behavior.
Why is the stateful FX program hard to test at first?Because it contains I/O side effects, especially the HTTP call and console interaction. Those side effects make it difficult to supply predictable inputs and observe outputs in tests.
How does refactoring with Try improve error handling?It wraps the rate lookup in a Try<decimal>, allowing failures to be represented explicitly instead of crashing the program. The stateful function then returns a Try of the rate and new state, making error handling safer and more composable.
What is a stateful computation?A stateful computation is a function that takes a state and returns both a value and a new state. It is also called a state transition.

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