Question

I'm having a bit of trouble understanding what the type parameters indicate in the case of the State monad, but also for the other mtl monads as well. Insofar as I understand it, when I compose a State monad, as in State String Int, what I really have is StateT String Identity Int. In the case of the method get for the MonadState typeclass, it returns m s, what is the 'm' in this case? Is it the Identity monad, Identity Int? And in this case is the 's' which represents the type of the state a parameter to the 'm'?

Thank you, I'm obviously having a bit of trouble understanding Haskell's type system.

Was it helpful?

Solution

Well it depends on what instance you use – that's the whole point of the type class!

class MonadState s m where
  get :: m s

In case of simply State, that's the monad you're in:

instance MonadState String (State String) where
  get :: State String String

...which is short for

instance MonadState String (StateT String Identity) where
  get :: (StateT String Identity) String

OTOH, it could also be

instance MonadState Int (StateT Int IO) where
  get :: StateT Int IO Int

OTHER TIPS

If we look at the definition of StateT:

class (Monad m) => MonadState s m | m -> s where
    get :: m s
    put :: s -> m ()

Which has an instance for StateT defined as

instance (Monad m) => MonadState s (StateT s m) where
    get = StateT.get
    put = StateT.put

Then we say that

type State s a = StateT s Identity a

then we know that in this case, m ~ Identity. For your case of State String Int, we can also infer that s ~ String and a ~ Int, so the type of get is Identity String and the type of put is Identity ().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top