title: How can I write a state monad that does error handling as well?
body: <p>I need to write a state monad that can also support error handling. I was thinking of using the Either monad for this purpose because it can also provide details about what caused the error. I found a definition for a state monad using the Maybe monad however I am unable to modify it to use Either, instead of Maybe. Here's the code:</p>
  
  <pre><code>newtype StateMonad a = StateMonad (State -&gt; Maybe (a, State))
  
  instance Monad StateMonad where
  (StateMonad p) &gt;&gt;= k = StateMonad (\s0 -&gt; case p s0 of 
                                   Just (val, s1) -&gt; let (StateMonad q) = k val in q s1
                                   Nothing -&gt; Nothing)
  return a = StateMonad (\s -&gt; Just (a,s))
  
  data State = State
  { log  :: String
  , a    :: Int}
  </code></pre>