I am trying to print inside the State
monad by using liftIO
function from MonadIO
class:
import Control.Monad.State
import Control.Monad.IO.Class
import Control.Applicative
facHelper :: Integer -> State Integer ()
facHelper 0 = pure ()
facHelper n = do
currentState <- get
liftIO $ putStrLn $ "n = " ++ show currentState
modify (*n)
facHelper (n-1)
factorial :: Integer -> Integer
factorial n = snd (runState (facHelper n) 1)
main :: IO ()
main = print $ factorial 6
However, I get the error:
No instance for (MonadIO Data.Functor.Identity.Identity) arising from a use of ‘liftIO’
If I look up MonadIO
class:
I see an instance:
MonadIO m => MonadIO (StateT s m)
And also see that State s
is a type alias
type State s = StateT s Identity
So, in principle, I could use liftIO
with State
. Where is the problem ?
factorial 6
) that you want to doIO
, but whose type doesn't mentionIO
anywhere (likeInteger
), you know you've screwed up. There is a sense in which the entire point of theIO
family of types is that it can't be escaped.Debug.Trace
instead. You can dotraceM $ "n = " ++ show currentState
to help debug logic in any monad without having to modify it to use IO.