我需要编写一个也可以支持错误处理的状态monad.我正在考虑将Either monad用于此目的,因为它还可以提供有关导致错误的原因的详细信息.我发现使用也许单子的状态单子的定义,但我无法修改为使用,而不是可能.这是代码:
newtype StateMonad a = StateMonad (State -> Maybe (a, State))
instance Monad StateMonad where
(StateMonad p) >>= k = StateMonad (\s0 -> case p s0 of
Just (val, s1) -> let (StateMonad q) = k val in q s1
Nothing -> Nothing)
return a = StateMonad (\s -> Just (a,s))
data State = State
{ log :: String
, a :: Int}
Run Code Online (Sandbox Code Playgroud)