简体   繁体   中英

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 (eg 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM