Lift to fix the *inside* of a monad transformer stack

前端 未结 1 1635
野性不改
野性不改 2021-01-06 16:53

Suppose I have an IO Int wrapped in a StateT MyState, then I have a value of State MyState Int which I want to use in the stacked mona

相关标签:
1条回答
  • 2021-01-06 17:42

    You have two options:

    1. Find a monad morphism. This is often a matter of finding the right library; in this case hoist and generalize together should get you where you need to go.
    2. Make your State action more polymorphic. This is the commonly used one, and the recommended one; it amounts to pre-applying the morphism from part 1, but has a lot of machinery put in place already in the mtl library to make it easy. The idea here is that if you write your State action just in terms of get, put, and modify, then instead of the type State s a, you can give it the type:

      MonadState s m => m a
      

      Then later, at the call site, you can choose whatever monad is appropriate for this, including both State s a and StateT s IO a. Moreover, since it specializes to the type State s a, you can be sure it doesn't do any IO or anything like that that State s a itself couldn't do, so you get the same behavioral guarantees.

    0 讨论(0)
提交回复
热议问题