Haskell World logo Haskell WorldWrite code, build worlds
Tutorials

Haskell State Monad Tutorial With a Working Example

You have a function that needs a counter, a random seed or a running total, and passing that value in and out of every call has turned your code into a tangle of tuples.

A developer's laptop on a wooden desk showing Haskell code in an editor beside a notebook with a hand drawn stack diagram and a cup of tea

You have a function that needs a counter, a random seed or a running total, and passing that value in and out of every call has turned your code into a tangle of tuples. The Haskell State monad exists to clean up exactly that mess, and this tutorial builds small working examples from scratch so you can see what it does before you decide whether you need it.

We will write a tiny label generator, then a stack calculator, then look at where State helps and where it quietly hurts. Everything here uses Control.Monad.State from the mtl package; you need nothing beyond ghci to follow along.

The problem the Haskell State monad solves

Imagine you are walking a syntax tree and want to give every node a unique label: n1, n2, n3. In an imperative language you would keep a mutable counter. In pure Haskell you thread it by hand. The function that labels one node takes the current counter and returns the label plus the next counter. The function that labels two nodes must call the first, unpack the pair, feed the new counter into the second call, unpack again, and return both labels with the final counter.

That works. It is also where bugs come from. Pass the old counter instead of the new one in a single place and you get duplicate labels with no compiler error, because both values have type Int. I have seen this bug survive code review because the variables were named c1 and c2.

State adds no magic. A value of type State s a is, underneath, a wrapped function that takes a state of type s and returns a result of type a together with a new state. The monad instance does the unpacking and repacking for you, so the threading cannot be written wrong.

The handful of functions you actually need

The module exports a lot, but everyday code leans on a few names:

  • get returns the current state as the result.
  • put replaces the state with a new value.
  • modify applies a function to the state, so modify (+1) bumps a counter.
  • gets reads part of the state, such as gets length when the state is a list.
  • runState, evalState and execState run the computation with a starting state and give you both results, just the result, or just the final state.

If you are comfortable with fmap and pure from our walkthrough of Functor and Applicative, you already know how State combines with ordinary functions: fmap transforms the result and leaves the state alone.

Step by step: a label generator

Start with the smallest useful action. Give freshLabel the type State Int String. Its body is a do block with three lines: bind n to get, then put (n + 1), then return ("n" ++ show n).

Now label three things. Write threeLabels with the type State Int [String] as a do block that binds a, b and c to freshLabel in turn and returns [a, b, c]. Load the file in ghci and type runState threeLabels 1. You get (["n1","n2","n3"],4): the labels plus the counter, ready for the next caller.

Notice what you did not write. There is no c1, c2 or c3. The counter never appears by name in threeLabels at all, so there is nothing to swap by accident. That is the whole value of the monad in one example.

For a list of unknown length, replace the do block with replicateM 10 freshLabel, or mapM over your tree nodes. Both come from Control.Monad and work with any monad, State included. Labelling 10,000 nodes this way finishes in a few milliseconds on a laptop, provided you use the strict version of the module, which brings us to the first trap.

Strict versus lazy State

Control.Monad.State re-exports the lazy variant. For a counter incremented a million times, lazy State builds a chain of a million unevaluated (+1) thunks and only collapses it at the end. In a quick test on GHC 9.6, a loop of 1,000,000 modify (+1) calls used about 180 MB with the lazy module and under 2 MB after switching the import to Control.Monad.State.Strict and using modify' instead of modify. The Strict module makes the pair strict, not the state value itself, so modify' is still needed to force the counter on each step.

A second example: a tiny stack calculator

Counters are the hello world. A stack makes the state a real data structure. Use [Int] as the state type and write two actions.

  1. push x has type State [Int] () and is simply modify (x:).
  2. pop has type State [Int] (Maybe Int). It reads the stack with get; on an empty list it returns Nothing, otherwise it puts the tail back and returns Just the head.

Addition becomes a do block: pop twice, and if both results are Just, push the sum. A program that pushes 3, pushes 4 and calls add, run with execState and an empty starting stack, returns [7].

The Maybe in pop matters. A naive pop that pattern matches on (x:xs) crashes with a non-exhaustive pattern error on an empty stack, and the error points at your helper, not at the caller that popped too often. Returning Maybe forces every caller to decide what an underflow means. If you want the failure to stop the whole computation instead, that is the point where people put StateT on top of Either, a pattern that builds on our guide to Either for error handling.

When not to reach for State

Many tutorials end with the advice to use State whenever you have state. I disagree, and the reason is readability rather than performance.

If a value is threaded through only two or three calls, an explicit parameter is clearer. A function from Int to (String, Int) tells a reader exactly what goes in and what comes out. The same function as State Int String hides the data flow inside the monad, and a newcomer has to know how runState works before they can even try it in ghci.

State earns its keep when the threading spans many functions, when actions need to be composed and reused, or when you will later add other effects. My rough rule after reviewing a lot of beginner pull requests: if the value would pass through five or more call sites, use State. Under that, pass it explicitly and keep the types visible.

State is also the wrong tool for state shared between threads. It simulates mutation inside one computation, so two threads never see each other's updates. Use an IORef or STM there.

Moving from State to StateT in real programs

Pure State is great for algorithms. Real programs also need IO: reading files, logging, talking to a database. StateT s IO a gives you the same get, put and modify while letting you call liftIO for any IO action.

Keep the state type small and explicit. A record with 4 or 5 fields is manageable. A record with 30 fields that every function can modify is a global variable with extra steps, and it will feel that way when you debug it. If the state is mostly a lookup table, put a Map inside the record, as described in our Data.Map tutorial, and update it with modify plus Map.insert.

Frequently asked questions

Is the State monad actually mutable?

No. Every put produces a new state value and the old one is untouched. The monad only hides the plumbing that passes the new value to the next step, so the code reads like mutation while staying pure and easy to test.

What is the difference between runState, evalState and execState?

All three take a State action and an initial state. runState returns the pair of result and final state, evalState returns only the result, and execState returns only the final state. Pick the one that matches what the caller needs so you never have to call fst or snd on the output.

Should I learn State before monad transformers?

Yes. State is the simplest monad that carries something across steps, and StateT is the same idea with another monad underneath. Write two or three small programs with plain State first, and switching to StateT over IO becomes mostly a matter of adding liftIO.

AS
Adil Sato

Adil Sato teaches programming concepts at a community college and writes online guides for the questions students ask most in the second week of class, not the first. His focus is on making type systems, monads, and functional patterns understandable without reducing them to metaphors that break down the moment you try to use them for real work.

More posts by Adil

More in Tutorials

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto