diff options
author | Hécate <hecate+gitlab@glitchbra.in> | 2020-03-23 14:21:39 +0100 |
---|---|---|
committer | Marge Bot <ben+marge-bot@smart-cactus.org> | 2020-04-09 23:10:44 -0400 |
commit | 045139f40089f288866c1c59c7379be82ecdaf34 (patch) | |
tree | 10e2c32e3ae2145ac5117a1ec22db8da7c5de30c /libraries | |
parent | dce50062e35d3246b63fba9357dea6313c23c780 (diff) | |
download | haskell-045139f40089f288866c1c59c7379be82ecdaf34.tar.gz |
Add an example to liftIO and explain its purpose
Diffstat (limited to 'libraries')
-rw-r--r-- | libraries/base/Control/Monad/IO/Class.hs | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/libraries/base/Control/Monad/IO/Class.hs b/libraries/base/Control/Monad/IO/Class.hs index 76806e132d..73520ed7b4 100644 --- a/libraries/base/Control/Monad/IO/Class.hs +++ b/libraries/base/Control/Monad/IO/Class.hs @@ -30,8 +30,42 @@ module Control.Monad.IO.Class ( class (Monad m) => MonadIO m where -- | Lift a computation from the 'IO' monad. + -- This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations + -- (i.e. 'IO' is the base monad for the stack). + -- + -- === __Example__ + -- + -- + -- > import Control.Monad.Trans.State -- from the "transformers" library + -- > + -- > printState :: Show s => StateT s IO () + -- > printState = do + -- > state <- get + -- > liftIO $ print state + -- + -- + -- Had we omitted @'liftIO'@, we would have ended up with this error: + -- + -- > • Couldn't match type ‘IO’ with ‘StateT s IO’ + -- > Expected type: StateT s IO () + -- > Actual type: IO () + -- + -- The important part here is the mismatch between @StateT s IO ()@ and @'IO' ()@. + -- + -- Luckily, we know of a function that takes an @'IO' a@ and returns an @(m a)@: @'liftIO'@, + -- enabling us to run the program and see the expected results: + -- + -- @ + -- > evalStateT printState "hello" + -- "hello" + -- + -- > evalStateT printState 3 + -- 3 + -- @ + -- liftIO :: IO a -> m a -- | @since 4.9.0.0 instance MonadIO IO where liftIO = id + |