title: How to inject the result of an IO action into a non-IO monadic computation
body: <p>I have a small bit of an architectural problem for which I'd like to see if there's a common pattern or abstraction that can help me. I'm <a href="http://www.github.com/Mokosha/Lambency">writing a game engine</a> where the user is able to specify a game loop as a monadic computation of the form:</p>
  
  <pre><code>gameLoop :: TimeStep -&gt; a -&gt; Game a
  </code></pre>
  
  <p>where the <code>Game</code> monad has a bunch of access points for drawing, transforming, and interfacing with the engine in general. Then, I also provide a function that the user calls to run the simulation</p>
  
  <pre><code>runGame :: (TimeStep -&gt; a -&gt; Game a) -&gt; a -&gt; IO a
  </code></pre>
  
  <p>One of the main design goals of the library was to not make <code>Game</code> an instance of the <code>MonadIO</code> typeclass. This is to prevent the user from shooting themselves in the foot by changing the state of the underlying graphics calls, or loading things when they're not expected. However, there are often use cases where the result of an <code>IO a</code> is useful after the game loop has already begun. In particular, spawning enemies with procedurally generated graphical elements comes to mind.</p>
  
  <p>As a result, I'd like to allow the user to request resources using something similar to the following interface:</p>
  
  <pre><code>data ResourceRequestResult a
    = NotLoaded
    | Loaded a
  
  newtype ResourceRequest a = ResourceRequest {
    getRequestResult :: Game (ResourceRequestResult a)
  }
  
  requestResource :: IO a -&gt; Game (ResourceRequest a)
  </code></pre>
  
  <p>With this, I'd like to fork a thread to load the resource and pass the result to the context of the <code>Game</code> monad and back to the user. The main goal would be that I get to decide when the IO action takes place -- somewhere that I expect it to rather than in the middle of the game loop.</p>
  
  <p>One idea that I had in mind was to place another user-defined monad transformer on top of the <code>Game</code> monad... something like</p>
  
  <pre><code>newtype ResourceT r m a = ResourceT (StateT [ResourceRequest r] m a)
  </code></pre>
  
  <p>However, I believe that then specifying things in terms of <code>f :: ResourceT r Game a</code> becomes an API nightmare, as I'd have to support any possible combination of monad transformer stacks. Ideally I'd also like to avoid making <code>Game</code> polymorphic in <code>r</code>, as it would increase the verbosity and portability of the underlying <code>Game</code> functions as well.</p>
  
  <p>Does Haskell have any abstractions or idioms for something like this programming pattern? Is what I want not possible?</p>