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 a new project state-monad using the stack command with the simple template:
        stack new state-monad simple
  1. Open the file src/Main.hs; we will add our code here after the initial module declaration.
  2. Import the following modules:
        import Prelude hiding (Either(..))        import Data.Functor        import Control.Applicative        import Control.Monad
  1. Now, add the definition for the State Monad. A State Monad will store state s with the monad:
        data State s a = State { runState :: s -> (a, s) } 
  1. Now, we will write the Functor instance for the state. Writing the Functor instance is easy; we need to transform output a with the function f :: a -> b and produce b:
        instance Functor (State s) where        fmap f (State stateFunc) =  let nextStateFunction ...

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