|
|
|
|
|
by mezuzza
3714 days ago
|
|
I like to think of it as a way to combine monads. Two classic examples might be the State monad and the Maybe monad. So let's say you want to create a function that operates on some state and might return a value. These are clearly both monads that you've heard about in Haskell, but how do you use them together? The answer is to use a monad transformer. StateT is the state monad transformer that takes any other monad and adds state to it.
`StateT s m a' is a monad that adds a state of type s to a monad m. So `StateT Int Maybe a' is thing that when given an int which is its state, might return a value. This particular combination was a little esoteric, so I'm not sure what a great example of this would be. However, you could also think of a situation where you want to have some sort of read-only state (such as flags from the command line) and the ability to write to a log. In Haskell these are provided by the Reader and Writer monads. But again, you have two separate monads here and in order to actually make use of them, you'll need to combine them somehow. Enter a monad transformer. You can either transform a Writer monad with the ReaderT monad transform or transform a Reader monad with the WriterT transform. ReaderT r (Writer w) a
OR
WriterT w (Reader r) a
Both satisfy this use case. I think those two constructions should be equivalent and conceptually equal. Someone should correct me if I'm wrong and there is some actual reason that those are different. To my understanding, the difference is purely due to limitations of the language as opposed to the mathematical constructs. |
|