title: How does ArrowLoop work? Also, mfix?
body: <p>I'm fairly comfortable now with the rest of the arrow machinery, but I don't get how loop works. It seems magical to me, and that's bad for my understanding. I also have trouble understanding mfix. When I look at a piece of code that uses <code>rec</code> in a <code>proc</code> or <code>do</code> block, I get confused. With regular monadic or arrow code, I can step through the computation and keep an operational picture of what's going on in my head. When I get to <code>rec</code>, I don't know what picture to keep! I get stuck, and I can't reason about such code.</p>
  
  <p>The example I'm trying to grok is from <a href="http://www.soi.city.ac.uk/~ross/papers/notation.html">Ross Paterson's paper on arrows</a>, the one about circuits.</p>
  
  <pre><code>counter :: ArrowCircuit a =&gt; a Bool Int
  counter = proc reset -&gt; do
          rec     output &lt;- returnA -&lt; if reset then 0 else next
                  next &lt;- delay 0 -&lt; output+1
          returnA -&lt; output
  </code></pre>
  
  <p>I assume that if I understand this example, I'll be able to understand loop in general, and it'll go a great way towards understanding mfix. They feel essentially the same to me, but perhaps there is a subtlety I'm missing? Anyway, what I would really prize is an <em>operational</em> picture of such pieces of code, so I can step through them in my head like 'regular' code.</p>
  
  <p><strong>Edit</strong>: Thanks to Pigworker's answer, I have started thinking about rec and such as demands being fulfilled. Taking the <code>counter</code> example, the first line of the rec block demands a value called <code>output</code>. I imagine this operationally as creating a box, labelling it <code>output</code>, and asking the rec block to fill that box. In order to fill that box, we feed in a value to returnA, but that value itself demands another value, called <code>next</code>. In order to use this value, it must be demanded of another line in the rec block <em>but it doesn't matter where in the rec block it is demanded, for now</em>. </p>
  
  <p>So we go to the next line, and we find the box labelled <code>next</code>, and we demand that another computation fill it. Now, this computation demands our first box! So we <em>give it the box</em>, but it has no value inside it, so if this computation demands the contents of <code>output</code>, we hit an infinite loop. Fortunately, delay takes the box, but produces a value without looking inside the box. This fills <code>next</code>, which then allows us to fill <code>output</code>. Now that <code>output</code> is filled, when the next input of this circuit is processed, the previous <code>output</code> box will have its value, ready to be demanded in order to produce the next <code>next</code>, and thus the next <code>output</code>.</p>
  
  <p>How does that sound?</p>