Haskell World logo Haskell WorldWrite code, build worlds
Tutorials

Haskell Reader Monad Tutorial for App Configuration

You start a service with one configuration field, a database connection string. Six weeks later the record holds eleven fields: a base URL, a timeout, a log level, an HTTP manager, a feature flag, an API token.

A terminal running ghci beside a Haskell source file showing a ReaderT config type signature on a developer desk

You start a service with one configuration field, a database connection string. Six weeks later the record holds eleven fields: a base URL, a timeout, a log level, an HTTP manager, a feature flag, an API token. Every function that touches any of them takes a cfg argument, and so does every function that merely calls one of those functions. Last month a student showed me a module where fourteen of nineteen top level functions had cfg as their first parameter and nine of them never read it.

That is the problem the Reader monad solves, and it solves nothing else. This walkthrough builds a small working example in ghci, shows the three functions you actually use, then spends as much space on when Reader makes code worse, because the second question my students ask after "how" is "should I", and most tutorials stop before that.

What the plumbing looks like before Reader

Define a record called Config with three fields: apiBase as Text, timeoutMs as Int, and verbose as Bool. Write fetchUser with the type Config to Int to IO User. It uses apiBase and timeoutMs. Now write syncTeam with the type Config to TeamId to IO (), which calls fetchUser in a loop. syncTeam never reads a single field, but it has to accept Config so it can hand it down.

That middle layer is the cost. It is not a correctness problem; the compiler keeps you honest about types. It is a diff problem. Add a fourth field that fetchUser needs and nothing changes in the signatures, which is fine. But split Config into two records, or change the argument order, and every intermediate function gets touched in the same commit. In a 40 module project that is a 300 line diff where maybe 20 lines carry meaning.

Reader removes the pass through parameter and nothing more. A value of type Reader r a is a wrapped function from r to a. The monad instance threads that r into every step for you, so the argument stops appearing by name in functions that do not care about it.

The three functions you actually need

Control.Monad.Reader from the mtl package exports more than this, but everyday code leans on a small set.

  • ask returns the whole environment as the result of the computation.
  • asks takes an accessor and returns one field, so asks apiBase gives you just the base URL.
  • local runs a sub computation under a modified environment and restores the original afterwards.
  • runReader and runReaderT supply the environment and run the thing.

Rewrite the example. Give fetchUser the type Int to ReaderT Config IO User. Its body binds base to asks apiBase, binds ms to asks timeoutMs, then does the request in liftIO. Give syncTeam the type TeamId to ReaderT Config IO (). It calls fetchUser directly. There is no cfg in syncTeam, not as a parameter and not inside the body. At the top of your program you write runReaderT (syncTeam t) cfg exactly once, in main.

Load it in ghci and run runReader (asks timeoutMs) (Config "localhost" 2500 False). You get 2500. That is the entire mechanism. If the word monad still feels like a wall here, the ideas in our explanation of monads without metaphors cover the bind operation that makes this threading happen.

Where local earns its place

ask and asks are the obvious half. local is the part people discover late and then use constantly.

Say you want one noisy section of a sync job to log at debug level without changing the rest. Write local (\c to c { verbose = True }) (fetchUser uid) and the modified Config applies only inside those parentheses. The outer computation keeps its original environment, because local does not mutate anything; it calls the inner function with a different argument.

The clearest real use I have is a recursive renderer. A template engine I wrote for a grading tool carries an indentation depth in its environment. Rendering a nested block is local (\e to e { depth = depth e + 2 }) (renderChildren node). With an explicit parameter you have to remember to pass depth + 2 at every recursive call site, and I got that wrong twice in the first version, which produced output that looked almost right. With local the increment lives in one place and the restore is automatic.

The advice to reach for ReaderT on day one

A common recommendation, often called the ReaderT design pattern, is to make ReaderT Env IO the single monad of your whole application from the start. I teach against starting there, and the reason is not performance.

The reason is that ReaderT over IO hides which functions do what. Once every function in the codebase has type ReaderT Env IO a, the type signature stops telling you anything. Does sanitizeInput hit the network? Does computeScore read the database? Both have the same type now, and the only way to find out is to read the body, which is exactly the thing types were supposed to save you from. A function with the type Config to Text to Either Err Score is a function you can test with no setup at all. The ReaderT version needs an Env.

The other cost is teaching and onboarding. On a two person project with 3,000 lines, the explicit parameter version is readable by anyone who knows records. The ReaderT version requires knowing lift, liftIO, MonadReader and why asks exists next to ask. That is a real tax and it is paid by whoever joins next.

My rough rule after several years of marking student code: pass the parameter explicitly while fewer than about five functions need it, and move to Reader when the number of pass through functions, the ones that take the environment and never read it, climbs past four or five. That number is a judgment call rather than a measurement, and I have seen reasonable people set it at two and at fifteen.

Where Reader stops paying for itself

Reader is read only, and the moment you want to write to the environment it is the wrong tool. Needing a counter or an accumulating log means you want the State monad instead, or a mutable reference such as an IORef held inside the Reader environment, which is the usual shape for a connection pool or a metrics counter.

The second failure is the god environment. A record with twenty two fields where each handler reads three of them is a type that admits everything and documents nothing. When that happens, the fix is smaller environments plus a class constraint such as MonadReader r m with HasLogger r, so each function announces the part it needs. Wrapping primitive fields in distinct newtypes helps here too, for the same reasons set out in our notes on newtype patterns.

Third, Reader does not compose with effects on its own. A function that reads config and can fail needs ReaderT Config (Either Err) or ReaderT over ExceptT, and the ordering of that stack changes the semantics. That is a separate subject, handled in the monad transformers walkthrough.

A migration you can finish this week

Pick one module, not the whole project. Find the functions whose first parameter is your config record and that never mention it in their body. Those are the ones Reader is for.

Change their types from Config to a to b into a to ReaderT Config IO b and delete the parameter. Replace every use of a field in the leaf functions with asks and the accessor. The compiler will now point at every call site that still passes cfg, and you delete those arguments one by one. Finally, add one runReaderT at the boundary, usually in main or in the HTTP handler that already has the config in scope. In a 600 line module this took me about 40 minutes, and the diff was smaller than I expected because most of it was deletions.

Keep the pure core pure. Functions that take config and return a value with no IO are better left as plain functions, because they stay trivially testable. Reader is for the plumbing, not for the arithmetic.

FAQ

Is Reader faster than passing an argument?

No. After GHC inlines and specialises, both compile to roughly the same thing. Pick Reader for the shape of the code, not for speed.

What is the difference between ask and asks?

ask returns the whole environment, asks applies a function to it first. asks f is the same as fmap f ask, and the short form keeps call sites readable.

Can I use Reader without monad transformers?

Yes. Plain Reader r a works for pure computations and needs no lifting at all. You only need ReaderT once IO or another monad enters.

Should every function in my app use ReaderT?

I would not. Keep pure functions pure and reserve the transformer for the layers that actually carry the environment, so the types keep telling you something.

AS
Adil Sato

Adil Sato teaches programming concepts at a community college and writes online guides for the questions students ask most in the second week of class, not the first. His focus is on making type systems, monads, and functional patterns understandable without reducing them to metaphors that break down the moment you try to use them for real work.

More posts by Adil

More in Tutorials

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto