title: Lazy evaluation example in Hadley's "Advanced R" book
body: <p>Hadley's "Advanced R" book contains the following example that I have a hard time understanding.</p>
  
  <blockquote>
  <pre><code>add &lt;- function(x) {
    function(y) x + y
  }
  adders &lt;- lapply(1:10, add)
  adders[[1]](10)
  #&gt; [1] 20
  adders[[10]](10)
  #&gt; [1] 20
  </code></pre>
    
    <p>x is lazily evaluated the first time that you call one of the adder functions. At this point, the loop is complete and the
    final value of x is 10. Therefore all of the adder functions will add
    10 on to their input, probably not what you wanted!</p>
  </blockquote>
  
  <p>I check and it is indeed true that <code>x</code> within each <code>adders[[num]]</code> evaluates to <code>10</code>.</p>
  
  <pre><code>get("x", envir=environment(adders[[2]])) # = 10
  get("x", envir=environment(adders[[9]])) # = 10
  </code></pre>
  
  <p>But why? For example, when <code>adders[[2]]</code> is defined as the returned value of <code>add(2)</code>, at that moment <code>x = 2</code>. According to Hadley, "a function preserves the environment in which it was defined." So why didn't <code>adders[[2]]</code> preserve the environment in which <code>x = 2</code>? </p>