Overview

Chapter 13. State machines: verifying protocols in types

This chapter shows how to make protocols explicit in types by modeling systems as state machines. Rather than just describing computations, the types can record which operations are allowed, what state must exist before an operation runs, and how the state changes afterward. The central idea is that if a function’s type captures the protocol, then any definition that type-checks is guaranteed to follow that protocol. This makes type-driven development especially useful for systems that depend on correct ordering of actions, such as resource handling or communication between components.

The chapter first develops this idea with small finite-state examples, such as a door that can be open or closed and a vending machine with a larger but still structured state space. In both cases, operations are given types that encode their preconditions and postconditions, so invalid sequences become impossible to express without a type error. The text also demonstrates how interactive development with holes helps reveal the current state of a computation as a sequence is built step by step. These examples highlight how dependent types can describe not only values, but also the transitions between values in a precise and checkable way.

The second major part applies the same approach to a stack, where the relevant state is the stack’s height. By representing stack operations in a dependent type indexed by input and output size, the chapter shows how to prevent unsafe actions like popping from an empty stack. It then extends the model to a concrete implementation using Vect, and finally to an interactive stack-based calculator that combines state, console input, and looping while remaining total and safe. The result is a practical demonstration that dependent types can verify real protocols and invariants while still supporting executable programs.

Figure 13.1. A state transition diagram showing the high-level operation of a database. It has two possible states, Closed and Connected. Its three operations, Connect, Query, and Close, are only valid in specific states.

Figure 13.2. A state transition diagram showing the states and operations on a door

Figure 13.3. How each user input affects the contents of the stack

Summary

  • Data types can model state machines by using each data constructor to describe a state transition.
  • You can describe how a command changes the state of a system by giving the input and output states of the system as part of the command’s type.
  • Developing sequences of state transitions interactively, using holes, means you can check the required input and output states of a sequence of commands.
  • Types can model infinite state spaces as well as finite states.
  • Sequences of commands give verified sequences of state transitions because a sequence of commands will only type-check if it describes a valid sequence of state transitions.
  • You can represent mutable dependently typed state by putting the arguments to the dependent type in the state transitions. For example, you can use the length of a vector to represent the height of a stack.

FAQ

What is the main idea of Chapter 13, “State machines: verifying protocols in types”?The chapter shows how to represent allowed sequences of operations as types, so the compiler can verify that programs follow a protocol. By encoding states and transitions in the type of a command description, invalid operation sequences are rejected at compile time.
Why use a state machine model for resources like files or databases?Because many resources have valid and invalid usage patterns. For example, a file must be open before reading, and a database must be connected before querying. A state machine model makes those preconditions explicit and prevents illegal operations from type-checking.
How does the door example demonstrate tracking state in types?The door is modeled with two states, such as DoorClosed and DoorOpen. Each command, like Open, Close, or RingBell, is given a type that states which input state it requires and which output state it produces.
What does the type DoorCmd ty beforeState afterState mean?It means a command sequence that produces a value of type ty, starts in beforeState, and ends in afterState. This lets the type describe both the result of the computation and the state transition it performs.
Why can’t invalid sequences like opening a door twice type-check?Because the type of each operation constrains what state must come before it. After an Open, the state is DoorOpen, so another Open that expects DoorClosed no longer matches the required input state.
How do holes and interactive development help in building these programs?Holes let you write part of a sequence and ask Idris what type the remaining code must have. That reveals the current input and output states, helping you choose only operations that are valid at that point in the protocol.
How is the vending machine example different from the door example?The vending machine has an infinite number of possible states, because it tracks quantities of coins and chocolates rather than just a small finite set of states. Its commands therefore use values like Nat pairs to describe preconditions and postconditions precisely.
Why does the vending machine model use pattern matching on state variables?Pattern matching lets the program prove that the machine is in a required state before performing an operation. For example, Vend only works when there is at least one coin and one chocolate, so the function matches on states of the form (S p, S c).
What is the purpose of StackCmd in the stack example?StackCmd describes stack operations with the stack height in the type. Operations like Push, Pop, and Top specify how the height changes, so the compiler can ensure you never pop from an empty stack.
How does the stack-based calculator use dependent types to stay safe?It separates the command language from the interpreter and gives precise types to each stack operation and user action. The main loop can then only perform operations when the stack is large enough, making the program total and preventing crashes from invalid stack states or unsupported input.

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
  • Type-Driven Development with Idris Type-Driven Development with Idris 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
  • Type-Driven Development with Idris Type-Driven Development with Idris ebook for free