Closure (closures) in various languages

xiaoxiao2021-03-06  65

Author: huangpuzhuang.com>

http://www.ruby-cn.org/

2004/11/23

In a Martin Fowler on a closed package (http://martinfowler.com/bliki/closures.html, Chinese: http://www.ruby-cn.org/articles/closures.html), In an example, it is mainly written in the Ruby language. Later, there have been many versions of other languages. This article adds the various versions to make you read more.

Ruby

Excerpt from the original http://martinfowler.com/bliki/closures.html1.

DEF Managers (EMPS)

Return Emps.select {| e | e.ismanager}

end

2.

DEF Highpaid (EMPS)

Threshold = 150

Return Emps.select {| e | e.salary> threshold}

end

3.

Def Paidmore (Amount)

Return proc.new {| e | e.salary> Amount}

end

4.

HIGHPAID = PAIDMORE (150)

John = EMPLOYE.NEW

John.salary = 200

Print

HIGHPAID.CALL (John)

2.c # 2.0

Excerpted from: http://joe.truemesh.com/blog//000390.html

1.

Public List Managers (List EMPS) {

Return Emps.FindAll (delegate (Employee E) {

Return E.Ismanager;

}

}

2.

Public List Highpaid (List EMPS) {

INT thRESHOLD = 150;

Return Emps.FindAll (delegate (Employee E) {

Return E.SALARY> thRESHOLD;

});

}

3.

Public Predicate PAIDMORE (Int Amount) {

Return delegate (Employee e) {

Return E.SALARY> AMOUNT;

}

}

4.

Predicate Highpaid = PAIDMORE (150);

Employee john = new employee ();

John.salary = 200;

Console.writeline (HighPaid (John));

3.python

Excerpt from: http://ivan.truemesh.com/archives/000392.html

Direct Lambda functions

1.

Def Managers (Emps): Return Filter (Lambda E: E.ismanager, EMPS)

2.

Def Highpaid (Emps): Threshold = 150 Return Filter (Lambda E: E.SALARY> Threshold, EMPS)

3.

Def Paidmore (Amount): Return Lambda E: E.SALARY> Amount

4.

HIGHPAID = PAIDMORE (150) John = Employee () John.salary = 200PRINT HighPAID (John) Another way, with list included (List comprehensions)

1.

Def Managers (EMPS): Return [e for e in Emps if E.ismanager]

2.

DEF HIGHPAID (EMPS): Threshold = 150 Return [e for e in Emps if e.salary> threshold]

Chris Reed provides another way to avoid using lambda:

DEF PAIDMORE (AMOUNT):

DEF PAIDMORECHECK (E):

Return E.SAlary> Amount

Return PaiDmoreCheck

4.java

Excerpted from: http://joe.truemesh.com/blog//000390.html

JDK 1.5 support

Private class FindhightEmployees extends algorithms {

ConsTRAINT HIGHPAIDEMPLOYEE;

Public FindHighPaideMployESS (construint constraint) {

THIS.HIGHPAIDEMPLOYEEEEEE = ConsTRAINT;

}

Public Object Call (Object O) {

List Emps = (List) O;

Return Findall (EMPS, HIGHPAIDEMPLOYEE);

}

}

Private class paidmore usments constraint {

Private int sale;

Public paidmore (int sales) {

THIS.SALARY = SALARY;

}

Public Boolean Test (Object O) {

Return (Integer O) .intValue ()> SALARY;

}

}

Closure HighPaidFinder = New FindhightEmployees (New Paidmore (150));

List hightpaidemployees = highpaidfinder.call (myemployees);

转载请注明原文地址:https://www.9cbs.com/read-88364.html

New Post(0)