How to reorganize a program using the state monad transformer?

I finished (well, almost) my first more or less useful project in Haskell. It consists of several modules and almost all modules use a StateT

lot.

Large image: At the top level, I need to work with state and IO at the same time, so I am using the StateT myState IO

monad transformer . This is ok and my code magically "just works", but now I think that maybe the code is not perfect because a lot of functions in other modules are inside the monad transformer, so they can potentially do IO, although they are pretty clean by theirs character. And this is bad.

Can you advise me how to refactor the program so that I can somehow write functions in modules inside State

monad, without any IO

, but being able to combine this code with IO at the top level?

+3


source to share


1 answer


If your function only needs StateT, you can give it a signature like

incrementCounter :: (Monad m) => (StateT Counter m ())
incrementCounter = do count <- get
                      put (increment count)
                      return ()

      



So your function must work with any Monad m (and cannot rely on being IO). At the top level, you can instantiate m = IO.

+4


source







All Articles