Monad transformers

Two contexts at once

Real code needs IO and failure in the same function. A plain IO (Maybe a) forces a case at every step, because the two layers do not chain:

-- painful: unwrap IO, then unwrap Maybe, at every line -- load :: FilePath -> IO (Maybe String) -- nicer: one monad that does both -- load :: FilePath -> MaybeT IO String

A transformer is a monad built on top of another monad. It adds one capability to the base and keeps a single bind for the whole stack.

The transformer stack

The stack is read from the outside in: the outermost transformer is the last one applied. A missing file becomes a Nothing instead of an exception:

import Control.Applicative (empty) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Maybe import System.Directory (doesFileExist) load :: FilePath -> MaybeT IO String load path = do exists <- lift (doesFileExist path) liftIO (putStrLn ("checking " ++ path)) if exists then lift (readFile path) else empty

empty is the failure of the Maybe layer, and the rest of the block is skipped exactly as a Nothing would skip it.

lift

A base action has to be promoted into the stack. lift does that for one layer, and liftIO reaches through any number of layers down to IO:

import Control.Applicative (empty) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Maybe path = "input.txt" -- one layer up -- lift (readFile path) :: MaybeT IO String -- all the way to IO -- liftIO (putStrLn "hi") :: MaybeT IO ()

Prefer liftIO when the action is IO, because it does not care how deep the stack is. Use lift for anything else.

Running the stack

A stack is a description, so main has to peel the layers off. runMaybeT returns IO (Maybe a), which the runtime can execute:

import Control.Applicative (empty) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Maybe import System.Directory (doesFileExist) load :: FilePath -> MaybeT IO String load path = do exists <- lift (doesFileExist path) liftIO (putStrLn ("checking " ++ path)) if exists then lift (readFile path) else empty main :: IO () main = do result <- runMaybeT (load "input.txt") case result of Nothing -> putStrLn "missing" Just t -> putStrLn (show (length t))

The ExceptT variant is the same shape with an error value instead of Nothing, and runExceptT returns IO (Either e a). Lesson 46 compares the two with real exceptions.

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

Article author: Arthur Isaev