Note that there are some explanatory texts on larger screens.

plurals
  1. POMonads in monad transformer context
    primarykey
    data
    text
    <p>I have trouble gripping to monads and monad transformers. I have the following contrived example (not compilable):</p> <pre><code>import Control.Monad import Control.Monad.Error import Control.Monad.Reader data State = State Int Int Int type Foo = ReaderT State IO readEither :: String -&gt; Either String Int readEither s = let p = reads s in case p of [] -&gt; throwError "Could not parse" [(a, _)] -&gt; return a readEitherT :: IO (Either String Int) readEitherT = let p s = reads s in runErrorT $ do l &lt;- liftIO (getLine) readEither l foo :: Foo Int foo = do d &lt;- liftIO $ readEitherT case d of Right dd -&gt; return dd Left em -&gt; do liftIO $ putStrLn em return (-1) bar :: Foo String bar = do liftIO $ getLine defaultS = State 0 0 0 </code></pre> <p>If I copy the functionality of readEither to readEitherT, it works, but I have a nagging feeling that I can leverage the power of the existing readEither function, but I can't figure out how. If I try to lift the readEither in the readEitherT function, it lifts it to <code>ErrorT String IO (Either String Int)</code> as it should. But I should somehow get it to <code>ErrorT String IO Int</code>.</p> <p>If I'm going to the wrong direction with this, what is the correct way to handle errors which require IO (or other monads) and are to be called from monadic context (see the <code>foo</code> function in the example)</p> <p><strong>Edit:</strong> Apparently it was not clear what I was trying to do. Maybe the following function describes what and why I was wondering</p> <pre><code>maybePulseQuit :: Handle -&gt; IO (Either String ()) maybePulseQuit h = runErrorT $ do f &lt;- liftIO $ (communicate h "finished" :: IO (Either String Bool)) (ErrorT . pure) f &gt;&gt;= \b → liftIO $ when b $ liftIO pulseQuit </code></pre> <p>This works, but is still ugly because of the binds. This is a lot clearer than the previous version which had case checking. Is this the recommended way to do this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload