Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The basic approach would be to rewrite your <code>Op</code> monad as a monad transformer. This would allow you to use it in a "stack" of monads, the bottom of which might be <code>IO</code>.</p> <p>Here's an example of what that might look like:</p> <pre><code>import Data.Array import Control.Monad.Trans data Registers = Reg { foo :: Int } data ST = ST {registers :: Registers, memory :: Array Int Int} newtype Op m a = Op {runOp :: ST -&gt; m (ST, a)} instance Monad m =&gt; Monad (Op m) where return a = Op $ \st -&gt; return (st, a) (&gt;&gt;=) stf f = Op $ \st -&gt; do (st1, a1) &lt;- runOp stf st (st2, a2) &lt;- runOp (f a1) st1 return (st2, a2) instance MonadTrans Op where lift m = Op $ \st -&gt; do a &lt;- m return (st, a) getState :: Monad m =&gt; (ST -&gt; a) -&gt; Op m a getState g = Op $ \st -&gt; return (st, g st) updState :: Monad m =&gt; (ST -&gt; ST) -&gt; Op m () updState g = Op $ \st -&gt; return (g st, ()) testOpIO :: Op IO String testOpIO = do x &lt;- lift getLine return x test = runOp testOpIO </code></pre> <p>The key things to observe:</p> <ul> <li>The use of the <code>MonadTrans</code> class</li> <li>The use of the <code>lift</code> function acting on <code>getLine</code>, which is used to bring the <code>getline</code> function from the <code>IO</code> monad and into the <code>Op IO</code> monad.</li> </ul> <p>Incidentally, if you don't want the <code>IO</code> monad to always be present, you can replace it with the <code>Identity</code> monad in <code>Control.Monad.Identity</code>. The <code>Op Identity</code> monad behaves exactly the same as your original <code>Op</code> monad.</p>
    singulars
    1. This table or related slice is empty.
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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