What is the difference between different orderings of the same monad transformers?

前端 未结 5 1415
你的背包
你的背包 2021-01-31 18:09

I am attempting to define an API to express a particular type of procedure in my program.

newtype Procedure a = { runProcedure :: ? }

There is

5条回答
  •  感情败类
    2021-01-31 18:36

    Edit: I originally got the cases backwards. Fixed now.

    The difference between orderings of monad transformer stacks really only matters when you're peeling off layers of the stack.

    type Procedure a = MaybeT (State ProcedureState) a
    

    In this case, you first run the MaybeT, which results in a stateful computation which returns a Maybe a.

    type Procedure a = StateT ProcedureState Maybe a
    

    Here the StateT is the outer monad, which means that after running the StateT with an initial state, you'll be given a Maybe (a, ProcedureState). That is, the computation may have succeeded, or may not have.

    So which you choose depends upon how you want to handle partial computations. With MaybeT on the outside, you'll always get some sort of returned state regardless of the computation's success, which may or may not be useful. With StateT on the outside, you guarantee that all stateful transactions are valid. From what you describe, I would probably use the StateT variant myself, but I expect either could work.

    The only rule for monad transformer ordering is that if IO (or another non-transformer monad) is involved, it must be the bottom of the stack. Typically people will use ErrorT as the next lowest level if it's required.

提交回复
热议问题