3 ms·
If a monad is like giving some additional context to a value: Maybe a: "Either it's a value or nothing" [a]: "The value was obtained from a list of pos
by MichaelBurge 11y ago
If a monad is like giving some additional context to a value:
Maybe a: "Either it's a value or nothing"
[a]: "The value was obtained from a list of possible values"
IO a: "The value was obtained from a database somewhere"
Except ErrorType a: "The value is either an error message or a real value"
, then a monad transformer takes an existing monad and augments it with even more context:
ExceptT ErrorType IO a: "this value was obtained from a database somewhere, and also maybe there was an error message"
StateT ConnectionPool IO a: "this web server response value was calculated using a connection obtained from the server's stateful connection pool, and a database connection"
Most monads like State are actually defined as the monad transformer applied to the Identity monad, which has no special context at all:
State stateType returnType = StateT stateType Identity returnType
Additionally, IO is very common to bury at the bottom of one of these stacks, so there is 'liftIO' to run an IO action in a monad transformer stack. So your web server can just do:
liftIO $ putStrLn "Hello World"
if you need a quick log message. You need liftIO, because 'putStrLn "Hello World"' is of type IO (), and the web server needs type 'StateT ConnectionPool IO ()'.
Note: IO does more than just databases, of course.