IORef

A cell in IO

An IORef a is a mutable cell that lives in IO: it is created by an action, read by an action and written by an action. The four functions are the whole interface:

newIORef :: a -> IO (IORef a) readIORef :: IORef a -> IO a writeIORef :: IORef a -> a -> IO () modifyIORef' :: IORef a -> (a -> a) -> IO ()

The cell is not a variable in the C sense: a function cannot take one and change it behind your back, because every read and every write is an IO action and the type says so. What it buys is a value that outlives one function call, which a pure function cannot have.

newIORef, readIORef and modifyIORef

module Main (main) where import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef) main :: IO () main = do counter <- newIORef (0 :: Int) modifyIORef' counter (+ 1) modifyIORef' counter (+ 1) value <- readIORef counter print value writeIORef counter 10 print =<< readIORef counter

ghc -Wall -O1 -o counter counter.hs
./counter

2
10

newIORef returns the cell and not its value, and the two modifyIORef' calls change what the cell holds. The prime matters: modifyIORef without it stores the result as a thunk, so a long loop of updates builds a chain of thunks that is only evaluated when the value is finally read. The strict version evaluates first and is the one to use in a loop.

A counter passed to a function

The cell can be passed to a helper, which is how a counter is shared without a global variable:

module Main (main) where import Data.IORef (IORef, modifyIORef', newIORef, readIORef) type Counter = IORef Int bump :: Counter -> IO Int bump counter = do modifyIORef' counter (+ 1) readIORef counter main :: IO () main = do counter <- newIORef (0 :: Int) first <- bump counter second <- bump counter print (first, second) print =<< readIORef counter

ghc -Wall -O1 -o bump bump.hs
./bump

(1,2)
2

Two calls see the same cell and the numbers follow each other, so the function is not pure: the same argument gives a different answer on each call. That is visible in the type, which is why the caller is not surprised. In a single thread there is no race, but nothing stops a second thread from changing the cell between the modify and the read; the concurrency part of the course replaces the pair with an atomic operation or an MVar.

When to use an IORef

The state monad and an IORef can hold the same counter, and the choice is about who owns the state:

A cache is the honest example for an IORef: a Data.Map in a cell, read on every request and updated on a miss. The value is shared, the program is in IO, and the alternative is a global variable in a language that has them. The next lesson looks at arrays, which are the immutable counterpart of a mutable block of memory.

Exercises

  1. Count the calls of a function with an IORef and print the number at the end.
  2. Write a cache with IORef (Map String Int) and a function that computes on a miss.
  3. Explain what goes wrong with modifyIORef in a loop of a million updates and why the prime fixes it.
  4. Read the cell twice in a row without writing and compare the values.
  5. Write the same counter with State Int and say which version is easier to test.
  6. Explain why newIORef is an IO action and not a pure function.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does newIORef return?

    Answer

    An IO action that creates a cell

    Creating a cell is an effect, so the result is an IO action that gives the cell when it runs.

  2. What does readIORef return?

    Answer

    IO a, the current value

    Reading a mutable cell is an effect and the value can change between two reads.

  3. Why use modifyIORef&#39; instead of modifyIORef in a loop?

    Answer

    The strict version evaluates the new value instead of storing a thunk

    Storing a thunk per update builds a chain that leaks memory until the value is read.

  4. What does this program print? module Main (main) where import Data.IORef (modifyIORef', newIORef, readIORef) main :: IO () main = do ref <- newIORef (1 :: Int) modifyIORef' ref (* 3) print =<< readIORef ref

    Answer

    3

    The cell starts at 1 and the strict modification multiplies it by 3.

  5. Which type does an IORef Int hold?

    Answer

    Int

    The parameter of IORef is the type of the value in the cell.

  6. What does this program print? module Main (main) where import Data.IORef (newIORef, readIORef, writeIORef) main :: IO () main = do ref <- newIORef (1 :: Int) writeIORef ref 7 writeIORef ref 9 print =<< readIORef ref

    Answer

    9

    writeIORef replaces the value, so the last write wins.

  7. When is an IORef the right choice?

    Answer

    When the value must outlive one call or be shared, and the program is in IO

    A shared mutable cell fits IO code; a pure computation is better served by State or an argument.

  8. Can two threads share one IORef safely without more work?

    Answer

    No, an update is read and write and another thread can run between them

    An IORef is not atomic, so a shared counter needs an atomic operation, an MVar or STM.

  9. What does writeIORef ref value return?

    Answer

    IO ()

    The write is an effect with no useful result, so it returns unit in IO.

  10. Why is the same function on the same IORef not referentially transparent?

    Answer

    The cell changes between calls, so the same argument gives a different result

    The function reads shared mutable state, which is exactly what purity excludes, and the IO type makes it visible.

The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image