title: How to not fall into R's 'lazy evaluation trap'
body: <p>"R passes <a href="http://cran.r-project.org/doc/manuals/r-release/R-lang.html#Promise-objects" rel="nofollow noreferrer">promises</a>, not values. The promise is forced when it is first evaluated, not when it is passed.", see <a href="https://stackoverflow.com/a/15742559/2207840">this answer</a> by G. Grothendieck. Also see <a href="https://stackoverflow.com/questions/16129902/explain-a-lazy-evaluation-quirk?rq=1">this question</a> referring to Hadley's book.</p>
  
  <p>In simple examples such as</p>
  
  <pre><code>&gt; funs &lt;- lapply(1:10, function(i) function() print(i))
  &gt; funs[[1]]()
  [1] 10
  &gt; funs[[2]]()
  [1] 10
  </code></pre>
  
  <p>it is possible to take such unintuitive behaviour into account.</p>
  
  <p>However, I find myself frequently falling into this trap during daily development. I follow a rather functional programming style, which means that I often have a function A returning a function B, where B is in some way depending on the parameters with which A was called. The dependency is not as easy to see as in the above example, since calculations are complex and there are multiple parameters.</p>
  
  <p>Overlooking such an issue leads to difficult to debug problems, since all calculations run smoothly - except that the result is incorrect. Only an explicit validation of the results reveals the problem.</p>
  
  <p>What comes on top is that even if I have noticed such a problem, I am never really sure which variables I need to <code>force</code> and which I don't.</p>
  
  <p>How can I make sure not to fall into this trap? Are there any programming patterns that prevent this or that at least make sure that I notice that there is a problem?</p>