title: Mutable variables in closures in F#
body: <p>I am trying to port some code form java do F# that generates a grid of multidimensional points around a given point. I came up with this:</p>
  
  <pre><code>let gridGenerator midpoint stepSize steps = 
      seq {
          let n = Array.length midpoint
          let direction = Array.create n -steps
          let mutable lastIndex = n-1
          while lastIndex&gt;=0 do
              let next = midpoint |&gt; Array.mapi (fun i x -&gt; x+ direction.[i]*stepSize)
              while lastIndex&gt;=0 &amp;&amp; direction.[lastIndex]=steps do 
                  direction.[lastIndex]&lt;- (-steps)
                  lastIndex&lt;-lastIndex-1;        
              if lastIndex&gt;=0 then
                  direction.[lastIndex]&lt;-direction.[lastIndex]+1;
                  lastIndex &lt;- n-1;
              yield next;
      }
  </code></pre>
  
  <p>Apart from this code being horribly imperative (I would be grateful for hints how to fix it), I am getting a compilation error:</p>
  
  <blockquote>
    <p>Program.fs(18,15): error FS0407: The mutable variable 'lastIndex' is used in an invalid way. Mutable variables cannot be captured by closures. Consider eliminating this use of mutation or using a heap-allocated mutable reference cell via 'ref' and '!'.</p>
  </blockquote>
  
  <p>How can I fix this error? How can I make it more functional?</p>
  
  <p>EXAMPLE: For midpoint <code>[|0.0, 1.0|]</code>, step size <code>0.5</code> and steps <code>1</code> I expect (in any order really)</p>
  
  <pre><code>seq{[|-0.5, 0.5|], [|-0.5, 1.0|], [|-0.5, 1.5|], [|0.0, 0.5|], [|0.0, 1.0|], [|0.0, 1.5|], [|0.5, 0.5|], [|0.5, 1.0|], [|0.5, 1.5|]}
  </code></pre>
  
  <p>Please also note that this will be executed many times, so performance is critical.</p>