O'Reilly logo

Haskell Cookbook by Yogesh Sajanikar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Create new project state-monad-trans using the simple Stack template:
        stack new state-monad-trans simple
  1. Open src/Main.hs. We will be adding our state transformer here.
  2. Add the following imports after the initial module declaration:
        import Data.Functor        import Control.Applicative        import Control.Monad
  1. 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) }
  1. 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)) <$> func s        in StateT stateFunc
  1. Now, define an Applicative instance for our state transformer. We make ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required