Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 57 ยท Real-world Haskell

Project: Bank Account Simulator with State

Build a bank account simulator in Haskell with Either errors, the State monad and transaction replay, plus a runnable JavaScript model.

A bank is a classic way to practise state and errors. Accounts hold balances, transactions change them, and some transactions must be refused: you cannot withdraw more than you have, or deposit a negative amount. In an imperative language you would mutate a balance field and throw exceptions. In Haskell we keep everything pure and thread the state explicitly.

This project builds the simulator in three layers. First, a pure function that applies one transaction and returns Either BankError Accounts. Second, a replay function that applies a whole list of transactions. Third, a State version that keeps a ledger without passing the bank around by hand. You should know Maybe and Either, do-Notation and have seen State; here you use them together.

Real Haskell is read-only on this site. The runnable blocks are JavaScript stand-ins, including a small hand-written State monad so you can see what the library does under the hood.

Three layers

applyTx One transaction, pure, may fail.
Replay Fold a list of transactions.
State Keep a ledger of what happened.

Each layer reuses the one below.

1 / 2

Step 1: Types for money and mistakes

Never store money as Double: binary floating point cannot represent 0.10 exactly. Use whole cents in an Int (or Integer if you fear overflow).

HASKELL
import qualified Data.Map.Strict as Map

type Accounts = Map.Map String Int      -- balance in cents

data Tx
  = Deposit  String Int
  | Withdraw String Int
  | Transfer String String Int
  deriving (Show, Eq)

data BankError
  = NoSuchAccount String
  | InsufficientFunds String Int        -- account and its balance
  | BadAmount Int
  deriving (Show, Eq)

An error type with one constructor per failure reason lets callers react precisely and lets tests assert on exact values. Compare this with a String, which can only be displayed.

Step 2: Applying one transaction

Two helpers validate the pieces:

HASKELL
import Control.Monad (when)

checkAmount :: Int -> Either BankError ()
checkAmount n = when (n <= 0) (Left (BadAmount n))

findAccount :: String -> Accounts -> Either BankError Int
findAccount name accts =
  maybe (Left (NoSuchAccount name)) Right (Map.lookup name accts)

when cond action runs action only if cond holds, and does nothing (returns Right ()) otherwise, so checkAmount either passes or fails with Left. maybe converts a Maybe into an Either. Now the transaction logic reads like a script, and the first Left stops it:

HASKELL
applyTx :: Tx -> Accounts -> Either BankError Accounts
applyTx (Deposit name amount) accts = do
  checkAmount amount
  balance <- findAccount name accts
  pure (Map.insert name (balance + amount) accts)

applyTx (Withdraw name amount) accts = do
  checkAmount amount
  balance <- findAccount name accts
  when (balance < amount) (Left (InsufficientFunds name balance))
  pure (Map.insert name (balance - amount) accts)

applyTx (Transfer from to amount) accts = do
  afterWithdraw <- applyTx (Withdraw from amount) accts
  applyTx (Deposit to amount) afterWithdraw

The transfer is atomic for free. If the deposit fails (say the target account does not exist), the whole expression is a Left, and the caller still holds the original accts because nothing was mutated. No rollback code is needed.

JS applyTx with Either, modelled in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 3: Replaying a list of transactions

A transaction log is just a list, so processing it is a fold where each step may fail. foldM from Control.Monad is a fold for monadic steps: it threads the accumulator and stops at the first Left.

HASKELL
import Control.Monad (foldM)

replayAll :: Accounts -> [Tx] -> Either BankError Accounts
replayAll = foldM (flip applyTx)

foldM expects a function acc -> element -> m acc, but applyTx takes the transaction first, hence flip. This "all or nothing" replay is right for an audit: if any transaction in the batch is invalid, the whole batch is rejected.

Sometimes you want the opposite: apply what works, and report what did not. That needs state that survives errors, and it is where State helps.

Step 4: The State monad

State s a describes a computation that reads and updates a state of type s and produces an a. Underneath, it is nothing but a function s -> (a, s); the monad instance threads the state from one step to the next so you do not write that plumbing by hand. The key operations from Control.Monad.State (package mtl) are:

Operation Meaning
get read the current state
put s replace the state
modify f update the state with f
gets f read a part of the state
runState m s0 run it, returning (result, finalState)
evalState, execState keep only the result, or only the final state

We keep the accounts and a ledger of the transactions that succeeded:

HASKELL
import Control.Monad.State

data Bank = Bank
  { accounts :: Accounts
  , ledger   :: [Tx]          -- newest first
  } deriving Show

process :: Tx -> State Bank (Either BankError ())
process tx = do
  bank <- get
  case applyTx tx (accounts bank) of
    Left err -> pure (Left err)
    Right new -> do
      put (bank { accounts = new, ledger = tx : ledger bank })
      pure (Right ())

replay :: [Tx] -> Bank -> ([Either BankError ()], Bank)
replay txs = runState (mapM process txs)

mapM process txs runs process on every transaction in order and collects one result per transaction. A failed transaction returns Left but does not touch the state, so later transactions still run. After replay, the first component says which transactions failed and why, and the second holds the final bank.

The same logic with modify and gets is shorter when a step cannot fail, for example a helper that reports the total money in the bank:

HASKELL
totalCents :: State Bank Int
totalCents = gets (sum . Map.elems . accounts)

For code where errors should stop everything and state should be kept, you would stack the monads as ExceptT BankError (State Bank), which is the subject of State, Reader, Writer and Monad Transformers.

JS A hand-made State monad and the replay

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The state never changes in place: each step receives a state and returns a new one. bind is the plumbing that Haskell's State instance hides behind do.

Step 5: Testing the invariants

Money problems love invariants, and they are easy to test on pure code. With QuickCheck you can state them as properties (see Testing: HUnit, Hspec and QuickCheck):

HASKELL
-- A transfer never creates or destroys money
prop_transferConservesMoney :: Tx -> Accounts -> Bool
prop_transferConservesMoney tx accts =
  case applyTx tx accts of
    Left _ -> True
    Right new -> case tx of
      Transfer {} -> total new == total accts
      _           -> True
  where total = sum . Map.elems

Ordinary example tests cover the error cases: withdrawing too much yields Left (InsufficientFunds "bob" 2500), and depositing -5 yields Left (BadAmount (-5)). Because the errors are values, shouldBe compares them directly.

Ideas for extending it

  • Add an OpenAccount transaction and a CloseAccount that requires a zero balance.
  • Record failed transactions in a second ledger field.
  • Use StateT Bank IO to print each result as it happens, and read transactions from a file.
  • Replace Int with a newtype Cents so you cannot add cents to a transaction count by mistake (see Records, newtype and Type Synonyms).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a failed Transfer leave the original accounts intact?

    applyTx builds a new Map or returns Left; the original Map is immutable, so no undo is needed.
  2. 2. What does foldM (flip applyTx) do when one transaction returns Left?

    foldM in the Either monad short-circuits at the first Left.
  3. 3. What is State s a underneath?

    State wraps a function that takes the old state and returns a result with the new state.
  4. 4. Why store money as cents in an Int?

    Binary floating point introduces rounding errors; whole cents are exact.

Summary

  • Model failures with a dedicated error type and return Either BankError from pure functions.
  • do in the Either monad gives early exit; when turns a condition into a possible Left.
  • Immutable data makes multi-step operations like transfers atomic without rollback code.
  • foldM replays a log with all-or-nothing semantics; mapM in State applies what works and records what failed.
  • State threads a value through a computation: get, put, modify, runState.

Next: Project: JSON Parser from Scratch.