Writing a State Monad
In this recipe, we will write our own State Monad. We will use the state monad to store the effect of cursor movements.
How to do it...
- Create a new project
state-monadusing thestackcommand with thesimpletemplate:
stack new state-monad simple
- Open the file
src/Main.hs; we will add our code here after the initialmoduledeclaration. - Import the following modules:
import Prelude hiding (Either(..))
import Data.Functor
import Control.Applicative
import Control.Monad- Now, add the definition for the State Monad. A State Monad will store state
swith the monad:
data State s a = State { runState :: s -> (a, s) } - Now, we will write the
Functorinstance for the state. Writing theFunctorinstance is easy; we need to transform outputawith the functionf :: a -> band produceb:
instance Functor (State s) where
fmap f (State stateFunc) =
let nextStateFunction s =
let (xa, s1) = stateFunc s
...