This is probably not what you want, but I would like to mention in passing that there is a very concise way to implement this:
{-
The reason for this is that under the hood, StateT implemented as:
newtype StateT sma = StateT { runStateT :: s -> m (a, s) }
If you specialize s in String and specialize m to Maybe , you get:
StateT String Maybe a ~ String -> Maybe (a, String)
... which matches your type.
StateT following instances are automatically provided for you:
instance Monad m => Functor (StateT sm) instance Monad m => Applicative (StateT sm) instance Monad m => Monad (StateT sm) instance Alternative m => Alternative (StateT sm)
... and we can specialize m in these cases to Maybe , because Maybe implements both Alternative and Monad :
instance Monad Maybe instance Alternative Maybe
... so that means StateT s Maybe automatically Functor , Applicative , Monad and Alternative without any extra work on our part.
The last part of the trick is GeneralizedNewtypeDeriving , which allows us to remove instances of a type class through the newtype shell. Since our base type StateT is Functor , Applicative , Monad and Alternative , we can automatically raise all instances of a class class using our new type by adding:
... deriving (Functor, Applicative, Monad, Alternative)
... and the compiler will redefine them for our new type, taking care to do all the wrapping and deployment of the new type for us.
So, if you want to figure out how to implement Applicative for your parser, you can learn how Applicative implemented for StateT and then deduce from it how to implement it for your parser type.