Tuesday, November 24, 2009

Closures

I keep hearing people talking about Closures but it always seemed hard to grasp it by just a cursory look at the material.For the uninitiated Wikipedia's definition is hard to grasp

What is a closure? In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.

Oh what is a first-class function?A programming language is said to support first-class functions (or function types or function literals) if it treats functions as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions. This concept doesn't cover any means external to the language and program (meta programming), such as invoking a compiler or an eval function to create a new function.

Now what the heck is a free variable?In computer programming, a free variable is a variable referred to in a function that is not a local variable or an argument of that function[1].


And what do you mean bound? In programming languages, name binding is the association of values with identifiers[1]. An identifier bound to a value is said to reference that value.

Oh finally what is a lexical environment?In computer programming, lexical environment or scope is an enclosing context where values and expressions are associated

Kinda still hard to get if we don't know the formal terminology used

But from what I got and crudely put, Closure is the ability to be able to pass  a piece of "executable code" around and then the executable code when being executed will have access to the same set of variables as available to the place from where you are passing it .Here is a simple example in Ruby

def foo
        local_variable ="foo variable";   
       f = Proc.new { puts "local variable ="+local_variable}
       bar(f)     
 end

def bar(f)
      local_variable ="bar variable";   
      f.call
end

foo

This is going to print "local variable =foo variable" , so I was able to pass the { puts "local variable ="+local_variable} code around and wherever I executed it had access to the same variables as from where it was called i.e. foo

No comments: