title: F# quotations: variable may escape scope
body: <p>I have this bit of code:</p>
  
  <pre><code>let rec h n z = if n = 0 then z
                  else &lt;@ (fun x -&gt; %(h (n - 1) &lt;@ x + %z @&gt;)) n @&gt;
  </code></pre>
  
  <p>converted from a MetaOcaml example in <a href="http://www.cs.rice.edu/~taha/publications/journal/dspg04a.pdf">http://www.cs.rice.edu/~taha/publications/journal/dspg04a.pdf</a></p>
  
  <p>In the paper there is explained that the above example will yield the following with the parameters <code>3</code> and <code>.&lt;1&gt;.</code> (in MetaOcaml notation):</p>
  
  <pre><code>.&lt;(fun x_1 -&gt; (fun x_2 -&gt; (fun x_3 -&gt; x_3 + (x_2 + (x_1 + 1))) 1) 2) 3&gt;.
  </code></pre>
  
  <p>As you can see the <code>x</code>´s gets replaced by <code>x_1</code>, <code>x_2</code> etc. because the <code>x</code> would otherwise only refer to the <code>x</code> in the innermost <code>fun</code>.</p>
  
  <p>But in F# this isn't allowed. I get the compile-time error: "The variable 'x' is bound in a quotation but is used as part of a spliced expression. This is not permitted since it may escape its scope." So the question is: how can this be changed so it will compile and have the same semantic as the MetaOcaml output?</p>
  
  <p><em>Update to comment:</em> I use the PowerPack to actually evaluating the quotation. But I don't think this have anything to do with it because the error is at compile-time. So far QuotationEvaluation works. However, I do know it may not be the most efficient implementation.</p>
  
  <p><em>Update to Tomas´ answer:</em>
  I really don't want the <code>x</code> to be global, or to escape scope. But I want is the equivalent to</p>
  
  <pre><code>let rec h n z = if n = 0 then z
                  else (fun x -&gt; (h (n - 1) (x + z))) n
  </code></pre>
  
  <p>with quotations. Your answer gives <code>(h 3 &lt;@ 1 @&gt;).Eval() = 4</code> where the above yields <code>h 3 1 = 7</code>. And here, I want <code>7</code> to be the answer.</p>