Closures

As I already mentioned, the function result depends on parameters. Is this dependency exhaustive? Certainly not. The function definition exists in a lexical context and is free to use some entities from this context in the course of the transformation of arguments into the result. Let's consider the following code example (Ch3_5.fsx):

let simpleClosure = 
  let scope = "old lexical scope" 
  let enclose() = 
    sprintf "%s" scope 
  let scope = "new lexical scope" 
  sprintf "[%s][%s]" scope (enclose()) 

The preceding enclose() function does not have any parameters except unit. However, the result that's returned depends on the free value scope that was in the lexical scope at the time of the function definition. Let scope value be bound to the "old lexical ...

Get F# 4.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.