How to add IO to my own monad in Haskell?

I am new to Haskell. I wrote my own monad, which is a state monad with error handling:

newtype MyMonad a = MyMonad (State -> Either MyError (State, a))

I use it in a small language interpreter. Now I want to add some I / O operations to my language (read / write), but I don’t know how to enclose the IO monad inside mine. I know that I can combine ErrorT, StateT, IO and achieve this result, but is there any other way to do this without them?

+5
source share
1 answer

You can see how StateT is implemented :

newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }

To align with the state IO, you simply put IOin place mand get the desired type: s -> IO (a,s).

, - s -> IO (Either e (a, s)) s -> IO (Either e a, s) , , .

, s -> Either e (IO (a, s)) monad .

, .

, , , () s: data M e a = M { runM :: Either e (IO a) }

:

unsafePerformIO :: IO a -> a
unsafePerformIO io = fromLeft $ runM $ do
  a <- M $ Right $ io
  M $ Left a

, , m .

IO , State. , Either e (s -> (a, s)) .

+6
source

All Articles