Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 57 ยท IO and the real world

Mutable State: IORef, MVar and ST

Learn when and how to use mutable variables in Haskell: IORef and modifyIORef', MVar for sharing, and the ST monad with STRef and STUArray.

Haskell prefers immutable data, and most programs never need anything else. Yet sometimes mutation is the right tool: a counter shared by callbacks, a cache, or an algorithm that is naturally written with an array you fill in place. Haskell supports this safely by putting mutation inside monads, so it shows in the types.

There are three levels to know. IORef is a mutable variable in IO. MVar is a mutable variable that is also safe to share between threads. And the ST monad gives you local mutation inside a function that is still pure from the outside. Real Haskell is read-only on this site; the runnable blocks are JavaScript stand-ins that model the same ideas.

IORef: a variable in IO

Data.IORef provides a box holding a value:

HASKELL
import Data.IORef

main :: IO ()
main = do
  counter <- newIORef (0 :: Int)
  writeIORef counter 10
  modifyIORef' counter (+ 1)
  modifyIORef' counter (* 2)
  value <- readIORef counter
  print value                 -- 22
Function Type
newIORef a -> IO (IORef a)
readIORef IORef a -> IO a
writeIORef IORef a -> a -> IO ()
modifyIORef' IORef a -> (a -> a) -> IO ()
atomicModifyIORef' IORef a -> (a -> (a, b)) -> IO b

Always prefer modifyIORef' (with the apostrophe) to modifyIORef. The plain version is lazy: it stores a growing chain of unevaluated (+ 1) thunks, and a loop that updates a counter a million times builds a million-deep chain that blows up when finally read. This is the classic space leak. The strict version evaluates the new value as it stores it.

An IORef is also how you give several closures a shared variable:

HASKELL
makeCounter :: IO (IO Int)
makeCounter = do
  ref <- newIORef 0
  pure $ do
    modifyIORef' ref (+ 1)
    readIORef ref

main :: IO ()
main = do
  next <- makeCounter
  a <- next
  b <- next
  print (a, b)     -- (1,2)

Because IO actions are values, next is an action you can run repeatedly, and each run sees the same hidden reference.

Three kinds of mutable state

IORef A variable in IO.
MVar A lock-protected variable for threads.
ST Local mutation, pure result.

Reach for them only when immutable code gets awkward.

1 / 2
JS IORef as a box (a stand-in)

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

No output.

MVar: sharing between threads

An MVar a is a box that is either empty or full. takeMVar empties it (and blocks while it is empty), and putMVar fills it (and blocks while it is full). That makes it both a variable and a lock:

HASKELL
import Control.Concurrent
import Control.Monad (forM_, replicateM_)

main :: IO ()
main = do
  total <- newMVar (0 :: Int)
  done  <- newEmptyMVar
  forM_ [1 .. 4] $ \_ -> forkIO $ do
    replicateM_ 1000 (modifyMVar_ total (pure . (+ 1)))
    putMVar done ()
  replicateM_ 4 (takeMVar done)
  readMVar total >>= print        -- 4000

modifyMVar_ takes the value, runs your function and puts the result back, even if the function throws, so the lock is never lost. Without the lock, four threads incrementing an IORef with read-then-write could lose updates. atomicModifyIORef' is the lighter option when the only shared state is one reference. The full story, including STM, is in Concurrency and Software Transactional Memory.

ST: mutation hidden inside a pure function

Some algorithms, such as sieves and in-place sorts, are much clearer or faster with mutable variables. The ST monad lets you use them without leaking effects:

HASKELL
import Control.Monad.ST
import Data.STRef

sumST :: [Int] -> Int
sumST xs = runST $ do
  ref <- newSTRef 0
  mapM_ (\x -> modifySTRef' ref (+ x)) xs
  readSTRef ref

sumST has an ordinary pure type. The mutation is invisible from outside, so callers can treat it like any other function. The magic is in the type of runST:

HASKELL
runST :: (forall s. ST s a) -> a

The s is a "state thread" tag that cannot escape. An STRef s Int created in one runST cannot be returned or used in another, because s would have to be the same everywhere; the type checker rejects such programs. That is how Haskell guarantees that the result depends only on the inputs.

STRef has the same operations as IORef: newSTRef, readSTRef, writeSTRef, modifySTRef'.

Arrays: STUArray

For arrays, Data.Array.ST offers mutable arrays. STUArray holds unboxed elements (plain Int or Bool, no thunks), the array type used in tight numeric loops. A prime sieve:

HASKELL
import Control.Monad
import Data.Array.ST
import Data.Array.Unboxed

sieve :: Int -> UArray Int Bool
sieve n = runSTUArray $ do
  arr <- newArray (2, n) True
  forM_ [2 .. n] $ \i -> do
    isPrime <- readArray arr i
    when (isPrime && i * i <= n) $
      forM_ [i * i, i * i + i .. n] $ \j ->
        writeArray arr j False
  pure arr

primesUpTo :: Int -> [Int]
primesUpTo n = [i | (i, True) <- assocs (sieve n)]

runSTUArray runs the ST action and freezes the finished array into an immutable UArray without copying. Use newListArray, readArray, writeArray and getBounds for the rest of the interface. The array package ships with GHC; for richer APIs the vector package has the same pattern (Data.Vector.Unboxed.Mutable).

JS A sieve with local mutation

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

No output.

When to use mutable state

Start with immutable data and recursion or folds. Reach for mutation when:

  • you need shared state across callbacks or threads (IORef, MVar, STM);
  • a profile shows that an immutable version is too slow, and an in-place array or counter fixes it (ST);
  • you are porting an algorithm that is defined by in-place updates.

Do not use IORef just to avoid passing an argument; that gives up the testability that purity buys. Prefer State when you want state threading that stays pure.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should you usually write modifyIORef' instead of modifyIORef?

    The lazy version stores an unevaluated computation each time. After many updates the chain is huge and evaluating it can exhaust memory.
  2. 2. What does runST give you?

    Mutation inside ST cannot escape, so the function using runST has a pure type.
  3. 3. What happens when an MVar is empty and a thread calls takeMVar?

    takeMVar blocks while the MVar is empty, which is what makes it usable as a lock or a channel.
  4. 4. Which array type is typically used in an ST sieve of Eratosthenes for fast Booleans?

    STUArray is an unboxed mutable array living in ST, ideal for tight loops over plain values.

Summary

  • IORef is a variable in IO; use modifyIORef' to stay strict.
  • MVar is a blocking box that doubles as a lock for threads; modifyMVar_ is exception-safe.
  • ST, STRef and STUArray allow local mutation inside a pure function through runST and runSTUArray.
  • The s type variable keeps mutable references from escaping.
  • Prefer immutable code first, and mutable state where sharing or performance requires it.

Next, we organize growing programs into files: Modules and Imports.