liveBook · Manning

Monad stack

As explained in Functional Design and Architecture: Examples in Haskell

A monad stack is a composition of nested monads that presents their combined effects through one monadic interface.

A single monadic script can use one monad directly, but an application may need several effects at once. A game action, for example, must update its board and print messages. A monad stack combines those effects by nesting monads with transformers, then presents the result as a monad that can be used with do-notation. section 2.1.2 section 7.2.3

Board state plus IO

In a Minesweeper-style game, `type BoardMonad a = StateT Board IO a` places board state over IO. A `revealCell` action uses `get` and `put` for the board, but must use `lift` to print: the enclosing do-block belongs to `StateT`, not directly to `IO`. Here, `lift` adapts an action from the inner monad for use in the outer one. section 7.2.3 section 7.2.3

Listing 7.7 Lifting of IO actions
import Control.Monad.State (get, put, lift)
  
revealCell :: (X, Y) -> BoardMonad ()
revealCell (x, y) = do
  board <- get
  
  lift (putStrLn ("Trying cell " <> show (x, y)))           #1
  
  case Map.lookup (x, y) board of
    Nothing            -> lift (putStrLn "No such cell.")
    Just (Revealed _)  -> lift (putStrLn "Already revealed.")
    Just (Hidden Bomb) -> lift (putStrLn "It's bomb! You loose!")
    Just (Hidden c)    -> do
      let newBoard = Map.insert (x, y) (Revealed c) board
      put newBoard
      lift (putStrLn "Cell revealed.")

The cell-reveal script shows the boundary: board operations run directly, while each console message is lifted. section 7.2.3

Each extra layer makes access more explicit. With `StateT Score BoardMonad`, the score is at the top, the board is one layer down, and IO is two layers down. An action can therefore use `get` for the score, `lift get` for the board, and `lift (lift ...)` for printing. A single `StateT (Score, Board) IO` is also valid—and may be simpler, clearer, and more convenient. Add layers when their separation earns the extra lifting. section 7.2.3

Running a stack also proceeds layer by layer. `runStateT`, `execStateT`, and `evalStateT` select a value, a final state, or both while returning an action in the inner monad. Tests can run a board action with an initial board and check the result; a score-over-board action needs a second run to reach IO. section 7.2.3

A web handler with separate responsibilities

A Servant handler can use `ReaderT Runtime Handler`, where `Handler` is `ExceptT ServerError IO`. The Reader layer supplies the runtime for a business-logic scenario; the exception layer handles server errors; IO performs impure calls. The handler lifts through layers to run the scenario, then can convert a caught exception into an HTTP error at the handler boundary. section 14.2.2 section 14.3

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Works through stack construction, lifting, and layer-by-layer running; notes that a single combined state can be simpler than two state layers.
Examples
Uses a Minesweeper board script, nested score and board state, stack-running tests, and a web handler that converts exceptions.
What it assumes
Assumes familiarity with monads and do-notation; introduces transformers as the means of combining effects.
What you can do after
Build it from scratch with StateT over IO, lift inner actions, and run each layer to test its resulting state.
How it connects
Connects monad transformers and do-notation to StateT, IO, ReaderT, ExceptT, and Servant handlers.

Also explained in

Compare how 2 books explain monad stack →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.