Jul 4, 2011

f# essential part 4 - closure

f# support closure. Here is the definition of closure

In computer science, a closure (also lexical closure, function closure or function value) is a function together with a referencing environment for the nonlocal names (free variables) of that function.

In f#, you can define functions within other functions. The inner function can use any identifier in scope, including identifiers defined in outer function. When the inner identifier return as result of the outer function, identifiers defined in outer function is still being captured by the inner function, the inner is called closure.

let buildGreet greeting  = 
    let prefix = Printf.sprintf "%s ," greeting
    let greet name = 
        Printf.sprintf "%s%s" prefix name
    greet //greet is a closure, even the it is return it can still access,


let getHelloMessage = buildGreet "hello"
let message = getHelloMessage "fred"
printfn "%s" message