1

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 ?

2
  • If you ever end up with a term (like factorial 6) that you want to do IO, but whose type doesn't mention IO anywhere (like Integer), you know you've screwed up. There is a sense in which the entire point of the IO family of types is that it can't be escaped. Nov 20 at 18:34
  • If you are doing this for temporary debugging purposes, check out Debug.Trace instead. You can do traceM $ "n = " ++ show currentState to help debug logic in any monad without having to modify it to use IO. Nov 20 at 18:51

1 Answer 1

4

If you want to do IO, then IO has to be at the bottom of your monad transformer stack. Here's the usual mtl-way of fixing things:

facHelper :: (MonadIO m, MonadState Integer m) => Integer -> m ()
-- same definition as before

factorial :: Integer -> IO Integer
factorial n = execStateT (facHelper n) 1

main :: IO ()
main = factorial 6 >>= print

This uses StateT Integer IO instead of State Integer (i.e. StateT Integer Identity).

If you're curious about the mechanical details of what went wrong with your approach:

  1. want MonadIO (State s)
  2. have type State s = StateT s Identity, therefore want MonadIO (StateT s Identity)
  3. have MonadIO m => MonadIO (StateT s m), and more specifically have MonadIO Identity => MonadIO (StateT s Identity), therefore want MonadIO Identity
  4. don't (and can't sensibly) have MonadIO Identity
2
  • Thank you so much Daniel ! When you say, "If you want to do IO, then IO has to be at the bottom of your monad transformer stack." what do you mean by "at the bottom" ?
    – F. Zer
    Nov 20 at 19:36
  • 2
    @F.Zer It has to be the base monad that gets transformed (perhaps by many other transformers in sequence). In a stack like FooT (BarT (BazT Quux))), Quux is the bottom of the stack. Nov 20 at 19:50

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.