Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applicative instance for State and other MTL monads?

Looking at the docs for Control.Applicative, I notice that they have instance declarations for certain monads (e.g. IO, Maybe and notably ST), but there are no instances for MTL monads such as State and RWS. Instead it looks like there's a general-purpose WrappedMonad type defined, which I'm guessing is to cover all other cases.

So here are my questions:

  1. Why aren't there Applicative instances for MTL monads? The best answer I've been able to find on my own so far is a three year old post, where somebody implemented these instances and was summarily ignored.

  2. What's the deal with WrappedMonad? I found a post on Reddit that explains it briefly, but I think I'm confused about how to use it.

Ultimately I'd like to be able to use State in an applicative style (as was recommended to me), but if I have to litter my code with WrappedMonad data constructors then it doesn't seem like a win. I could also ignore WrappedMonad entirely, and define the Applicative instance myself the same way that was done for IO, ST and so on: in terms of return and ap... But that seems goofy as well.

like image 947
mergeconflict Avatar asked Nov 03 '11 00:11

mergeconflict


2 Answers

That documentation is generated based solely on the contents of the base package, which does not contain State - so it does not contain Applicative instances for it. If you look in the MTL documentation, you'll see an Applicative instance listed.

Alternately, you can open up GHCi, import Control.Monad.State and Control.Applicative, and use :i Applicative to list the instances of Applicative or :i StateT to list the classes for which StateT has instances (State is a type alias for StateT with one of its parameters fixed). Either will show that there is indeed such an instance.

like image 128
mokus Avatar answered Nov 04 '22 16:11

mokus


The Applicative instances for the mtl monads can't be listed in the base docs, because there's no mtl available at that point. The good news is that mtl has Applicative instances StateT for example, since mtl-2.0.0.0.

like image 33
Daniel Fischer Avatar answered Nov 04 '22 18:11

Daniel Fischer