liveBook · Manning

Finite-state machine

As explained in Functional Programming in Scala, Second Edition

A state machine is a computational model whose behavior is determined by a current state and input-driven transitions.

A finite-state machine models behavior with immutable state and input-driven transitions. In a purely functional design, functions compute each next state from the previous one, while State removes sequencing boilerplate. section 6.6

A candy dispenser illustrates the model:

  • Accept a coin only when locked and candy remains; unlock the machine and increase its coins. section 6.6
  • Dispense candy only when unlocked and then lock the machine; ignore invalid inputs and every input when empty. section 6.6

Simulation interface

A simulation consumes a list of inputs and returns the final coin and candy counts through State[Machine, (Int, Int)]. section 6.6

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines states and transition rules, then applies them through State combinators in a candy-dispenser exercise.
Examples
Uses a locked or unlocked candy dispenser with coin and turn inputs, tracked candies, and accumulated coins.
What you can do after
Builds a finite-state simulation that processes inputs and returns final machine values through State.
How it connects
Connects State, immutable data structures, pure functions, and side-effect elimination.

Also explained in

Compare how 9 books explain finite-state machine →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.