Writing a State Monad transformer
In this recipe, we will write our own State Monad transformer from scratch. In the state transformer, we embed another monad into a State Monad. Hence, all actions are performed in the embedded monad, whereas the state transformer is responsible for keeping state.
How to do it...
- Create new project
state-monad-trans
using thesimple
Stack template:
stack new state-monad-trans simple
- Open
src/Main.hs
. We will be adding our state transformer here. - Add the following imports after the initial module declaration:
import Data.Functor import Control.Applicative import Control.Monad
- Define the State Monad transformer. Note how we embed
middle m (monad)
in the type:
newtype StateT s m a = StateT { runStateT :: s -> m (a, s) }
- Define the
Functor
instance for our state transformer:
instance Functor m => Functor (StateT s m) where fmap f (StateT func) = let stateFunc s = (\(xa,xs) -> (f xa, xs)) <$>...