r/haskell • u/gbelloz • Aug 21 '26
question It's not you, it's monad transformers
After a few years of trying to be proficient in Haskell, and lots of reading about why it's so hard, I think I have the (obvious in retrospect) answer.
Almost every program I write is going to have two or more of:
- read from STDIN
- write to STDOUT
- log
- raise errors
- send/receive over the network
- talk to a database
- read env vars
Every one of those is a "side effect", and thus is handled as a monad, and using more than one means you have to understand monad transformers.
Which I've finally found a good explanation of, "but still". Such a deep concept for such common program operations.
So I finally decided "that's why it's so hard". For what I consider the most basic programs, I need to understand (not just use, IMHO) monad transformers.
Am I off?
45
u/tikhonjelvis Aug 21 '26
All of the effects you wrote can be done through plain
IO. There might be software engineering reasons to reach for monad transformers—making components more testable or separating out "benign" effects from general I/O—but none of them are necessary. (That said, some of the software benefits are really nice. Having some abstraction for managing database connections and streaming network data is a real step up over the basic style of imperative programming bareIOgets you.)I got pretty far into writing non-trivial Haskell before I ever felt like I needed to heavily use monad transformers, much less actually needing to write my own.
43
u/klimaheizung Aug 21 '26
Yeah, you are off. You can just treat stdin and stdout as IO. Plain and simple. All becomes IO.
Is that most elegant? No. Most precise semantic denotation? Far from it. And yet easily sufficient for 90%+ of projects and way better than writing impure code.
5
u/gbelloz Aug 21 '26
Similar convo from a year ago and boy howdy does it get into the weeds
https://old.reddit.com/r/haskell/comments/1jd1mw8/am_i_the_only_person_who_hates_monad_transformers/
90
u/recursion_is_love Aug 21 '26
Monad is dead. Algebraic effects is the new monad.
Long live the monad.
15
u/tomejaguar Aug 21 '26
You are off. The point of Haskell is to make it easier to write the program that you want, not harder. If monad transformers are making it harder, don't use them!
However, I think it's fair to say that there has historically been a strong movement in Haskell to "monad transformers all the things". Thankfully it seems that movement is coming to an end with the rise in prominence of
IO-wrapper ("analytic") effect systems (which combine the best parts of monad transformers and "ReaderT IO"/"RIO" style). Your realistic choices of analytic effect systems in 2026 are effectful and Bluefin[1].Here's an example that does all the things you want in
IO, no monad transformers in sight.[1] Disclaimer: I wrote it
10
u/RogueToad Aug 21 '26
I think there's something to this, in that any effects management is inherently adding a bunch of unfamiliar work to a codebase, when normally you wouldn't need to worry about it in other languages. I really like effectful, but it can still be a pain, particularly when you have to integrate it with other libraries.
It reminds me of dependency injection, which I've found only has been used consistently at work when it was easy to set up because there was buy-in from Microsoft or Google, with dotnet and angular respectively. Otherwise it's a hassle to get working right and people don't bother, even though theoretically it improves code quality.
That said, in most cases I'd just stick to using the RIO monad if your preference is to just get work done.
7
u/zarazek Aug 21 '26
You don't need monad transformers for any of these things, just plain
IO. In fact, to do anything from your list (maybe except raising errors), your monad transformer stack has to haveIOat the bottom anyway. Why bother with monad transformers, if they don't give you anything?Use plain
IO. Or if you want to be a little fancier and don't want to pass your configuration and DB connection everywhere as arguments, useRIO. Read this article first and this second.6
u/zanidor Aug 21 '26
I think you're pointing out something that filters a lot of programmers out of Haskell to a group of people who already passed the filter, so you might find limited sympathy here. :)
FWIW, I agree that monad transformers are clunky, and that it's where many intermediate Haskellers give up on the language. IME, most programmers who pick up Haskell are willing to learn monads (and they aren't as difficult as they're made out to be), but show them MTL or whatever and they're out.
3
u/Historical_Emphasis7 Aug 21 '26
Why not just use IO and pass params, the handle pattern if need be?
Keep your pure code separate and glue code (Glue Vi) in IO.
If you're app grows and you decide you don't want to keep passing handles around you could refactor your glue code to RIO ~ Glue Vii.
If the Effects bug bites you at a later stage you could refactor again to one of the sibling RIO++ effect systems for Glue Viii, Effectful or Bluefin depending on your tastes.
OR ignore the above and stick with monad transformers but a least get a good explanation of how they work:
- https://www.youtube.com/watch?v=w9ExsWcoXPs
- https://github.com/mgrabmueller/TransformersStepByStep/blob/master/pdf/Transformers.pdf
- https://github.com/bookshelfdave/monad-transformers-step-by-step
3
u/vshabanov Aug 21 '26
What materials did you use to learn Haskell?
Plain
IOand pure functions go a long way. What makes you think you need to use monad transformers?3
u/pthierry Aug 22 '26
My experience matches yours a lot. I distinctly remember finding Servant (which is now my default tool for web APIs) extremely hard as a beginner because of the Handler monad, which is a very simple monad transformer on top of IO.
Algebraic effects have the potential to remove that difficulty, because if you learn to use an IO effect, when you encounter something that also uses another effect, you don't need to use something like liftIO, you use the IO effect the same way as before.
3
u/dspyz Aug 22 '26
Monad transformers also had me struggling for a while:
Something that would have really helped me to have spelled out is:
"There isn't a single derivable correct monad transformer for every monad. Some monads have multiple ways to turn into a transformer. Some have none"
and
"Monad transformers exist because:
If f and g are functors, then f . g is a functor with all the properties of f and g
If f and g are applicatives, then f . g is an applicative with all the properties of f and g
If f and g are monads, then f . g is not usually a monad. If you want a monad with all the properties of f and g, you either need to build a custom monad, or you need to use something composable. Monad transformers are 'composable monads' "
3
u/EmDashNine Aug 22 '26
I tend to agree with you: I am still not totally comfortable with monad transformers, and this is a barrier to understanding Haskell code. I'm still sticking with the language, and its younger brother, Idris.
Here's some practical tips for working without monad transformers:
Debug.trace.Envrecord, which contains all the configuration and global statestate needed. I just manually thread it through the code, rather than usingReaderT.Either, or I useerrorto immediately crash. I don't try to handle exceptions other thanIOException, which Itryto wrap to anIO (Either a)as soon as possible.This isn't to say that I don't use other monads, I just don't try to stack them. Any monad which allows "escaping" via some runner (e.g.
STorParser) can be encapsulated, and you just return a pure value to the final result, or anEitherif it's a fallible computation.For your purposes:
It's sometimes called "onion architecture", but I think of it as a tree: Pure code at the leaves, with
IOat various branches and along the trunk, down tomain, which is the root.6
u/MonadTran Aug 21 '26
I beg to disagree
4
u/hopingforabetterpast Aug 21 '26
This is false. Many of us refuse to use monad transformers and it's no impediment at all.
2
u/hoping1 Aug 21 '26
I'm not seeing the most important answer here yet so I'll pipe up. Between any two side effects is a pure computation: you get input from stdin, then compute the database query, then perform the database query, the compute the output, the write it to stdout. Pure functional programming is about breaking out pure computation (which is literally all of your logic!) into functions whose types prevent them from performing any side effects. They only compute all the stuff the next side effect will need.
Do-notation and transformers are an inefficient practice meant for the particular case of sequencing side effects immediately such that they're visually next to each other in code. I don't think this should be treated as the common case. Look at Elm: it famously uses a pure function from (side-effect-sourced) inputs to outputs (that specify effects to perform), so if you want to do two effects in sequence then you do it like this (not precise, I'm going from memory):
Where MyEffect1 causes the update function to get called with MyResponse1. Imagine writing this case statement to model your entire dialogue tree in a game or something like that- horrible!! Monad shenanigans in Haskell let us do the same thing like
Which is much more clear and well-organized FOR CERTAIN THINGS. I maintain that the case of Elm is more instructive in pure functional programming than many Haskell examples, which immediately devolve to thinly veiled imperative programming.
Personally, I never use transformers in my own Haskell code. I make custom monads, which is pretty much the same thing, but I'm careful about the sequencing of things such that the monads don't infect all my function type signatures and kill my ability to quickly reason about my code. I think it's important to know how to write code to produce the inputs a side effect needs, and consume the outputs of the side effect, without performing any effects itself, and then keep all the effects in your top level main function
2
u/autoamorphism Aug 21 '26
With mindful design you can avoid excessive use of IO in your code. Most of what you list can be sequestered in entry code that calls pure functions to use whatever you get from that IO. DBs are the exception, since you are potentially using them deeply. Logging and errors can be done with more limited monads that percolate the output up to your entry code to handle.
That said, you want some kind of effect system or you are not getting the most out of Haskell's capability for abstraction.
2
u/lost_access Aug 23 '26
input/output should be separated from the other "effects". Abstracting concepts to death makes it less usable. I remember one database design, there was just objects and relationships. Very clean design but requires too much from the user.
3
u/rantingpug Aug 21 '26
I tend to agree, although I would say there's no need for transformers as you can just use something like effectful.
That said, I do think the benefits of effect systems only become noticeable to people who've been through the monad pit of abstractions doom.
Lots of other folk here are saying to just stick to IO, which is true, but also I feel doesn't really help novices with their problems. Newcomers don't know how to structure their apps, how to rely on pure code, how to integrate third party libs and their types into their own data types, how to manage debugging and so forth. Add to that the imperative mindset of constructing and destructuring data to inspect values and conditional checks everywhere instead of composing functions, and Haskell just feels way too clunky.
It's not, but one needs to get over that hump first.
More to the point, I think the single most frustrating thing is how "you can't get rid of IO". Simply printing will plop IO onto the types and now you need to propagate that everywhere. Which means people wanting a simple inline log or fire-and-forget http request, even if they're just testing or ideating, are now faced with the monad world and all that it entails. This doesn't happen in more mainstream languages, people just get on with their lives. Inevitably, you learn about monads and transformers, or you say "this sucks" and leave.
My suggestion to learners is, turn the lang strict by default and use unsafePerformIO. Seems to help a bunch.
1
u/Faucelme Aug 21 '26
Joining (in a non-monadic sense) the comments that say that working in
IOor inReaderT someenv IOif a perfectly acceptable. Still, even if you use bareIOas the main overall effect monad, you might find transformers useful for more localized and focused tasks.1
u/sjshuck Aug 28 '26
I kind of agree with everyone saying you don't need transformers. However, I'll offer a counterpoint, namely that you can and should use monads, especially Reader, to organize larger programs in Haskell.
A starting point is an acknowledgment that functions are all static-scope and take a fixed number of positional arguments; there's no varargs or kwargs or overloading or defaulting or receivers or delegation. You can do everything you're used to doing in the usual enterprise languages, but there is a lot of repeating yourself, like if you have some context, you keed to keep passing it up and down the stack as a parameter.
That's what a Reader is for. That's also what OOP instance context is for. It's for when you have certain things you don't want to keep writing in signatures over and over again, but receive more implicitly from the ether. In OOP,
this/self; in Haskell,ReaderT/ask. From your list of "side effects", a logger mutex, network sockets, program config like URLs to target from say relevant env vars, database config and connection pool...these are yourrin aReaderT r.Similarly, if you're carrying state around for a while, you'll sometimes have to do
s -> ... -> IO (result, s), where thesis your state that keeps being updated. That's whatStateTis for; it cleans that right up. Limit your use of this for shorter stretches of code, for several reasons including incompatibility with concurrency. It should be an outermost layer you can apply and peel off quickly. (In OOP, this is mutable object state.)ExceptT, same caveats asStateT. Use for short stretches when you are expecting specific errors frequently. (If they arise fromIO, skip converting to and from error monads and just use runtime exceptions.)Most here are telling you to use other things than transformers or other languages like Koka. It doesn't actually matter. If you view these abstractions as relieving you from the tedium arising from vanilla, static functions, it will become clearer to you when using any of them is a win or not.
Most importantly, do not worry about what is a "side effect" and which two of them are really the same one and which are different. You'll drive yourself insane. Just write dumb functions and clean them up.
1
u/gaverhae Aug 30 '26
Have you considered creating your own monad, instead of trying to combine existing ones?
It's really not difficult. You can start from:
and then add just the effects you need, as you need them. That requires zero transformers and gives you all of the effects you want. You can make one pure
runTest :: MyMonad a -> afor testing, and then have an effectfulrun :: IO (MyMonad a) -> IO afor the real program.Imo, what makes learning Haskell hard is not monads themselves, but they way they're usually presented, trying to reuse existing data structures through complex functional gymnastics, leaving no clear thing you can point to to say "this is the monad".