CSC/ECE 517 Fall 2007/wiki1 2 pk: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 1: Line 1:
== Closures ==
== Closures ==
Closures are functions which are evaluated in an environment containing bound variables. They are usually found in languages which treat functions as first class values i.e. they can passed around as arguments to functions, bound to variables and even be returned from functions. Closures were initally developed in the 1960s in a language called Scheme and was later adopted in other languages including Ruby and Smalltalk.
Closures are functions which are evaluated in an environment containing bound variables. They are usually found in languages which treat functions as first class values i.e. they can passed around as arguments to functions, bound to variables and even be returned from functions. Closures were initally developed in the 1960s in a language called Scheme and later adopted in other languages including Ruby and Smalltalk.


Assume, we have list of employees and we want to find the list of employees who are managers. The following ruby code shows how this can be done with closures.
Assume, we have list of employees and we want to find the list of employees who are managers. The following ruby code shows how this can be done with closures.

Revision as of 16:28, 13 September 2007

Closures

Closures are functions which are evaluated in an environment containing bound variables. They are usually found in languages which treat functions as first class values i.e. they can passed around as arguments to functions, bound to variables and even be returned from functions. Closures were initally developed in the 1960s in a language called Scheme and later adopted in other languages including Ruby and Smalltalk.

Assume, we have list of employees and we want to find the list of employees who are managers. The following ruby code shows how this can be done with closures.

def managers(emps)
  return emps.select {|e| e.isManager}
end

However, the biggest advantage of closures is that they can refer to the variables which were visible at the time they were defined. An small example using closures is shown below, where we pick the employees who have a salary greater than a thershold.

def highPaid(emps)
  threshold = 150
  return emps.select {|e| e.salary > threshold}
end