本文共 2404 字,大约阅读时间需要 8 分钟。
作者:<liubin <AT>huangpuzhuang.com>
2004/11/23
在的一篇关于闭包的文章中(,中文版:),提到了一个例子,主要是用Ruby语言写的,后来网上出现了很多其它语言的版本,本文将各个版本摘录下来,方便大家阅读比较。
1.Ruby
摘自原文
1.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 = Employee.newjohn.salary = 200print highPaid.call(john)
2.c# 2.0
摘自:
1.
public ListManagers(List emps) { return emps.FindAll(delegate(Employee e) { return e.IsManager; }}
2.
public ListHighPaid(List emps) { int threshold = 150; return emps.FindAll(delegate(Employee e) { return e.Salary > threshold; });}
3.
public PredicatePaidMore(int amount) { return delegate(Employee e) { return e.Salary > amount; }}
4.
PredicatehighPaid = PaidMore(150);Employee john = new Employee();john.Salary = 200;Console.WriteLine(highPaid(john));
3.Python
摘自:
直接用lambda函数
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 > amount4.
highPaid = paidMore(150)
john = Employee()john.salary = 200print highPaid(john)另一种方式,用列表包含(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]提供了另一种避免使用lambda的方法:
def paidMore(amount): def paidMoreCheck(e): return e.salary > amount return paidMoreCheck
4.Java
摘自:
jdk 1.5支持
private class FindHighPaidEmployees extends Algorithms { Constraint highPaidEmployee; public FindHighPaidEmployess(Constraint constraint) { this.highPaidEmployee = constraint; } public Object call(Object o) { List emps = (List)o; return findAll(emps, highPaidEmployee); }}private class PaidMore implements Constraint { private int salary; public PaidMore(int salary) { this.salary = salary; } public boolean test(Object o) { return ((Integer)o).intValue() > salary; }}
Closure highPaidFinder = new FindHighPaidEmployees(new PaidMore(150));List highPaidEmployees = highPaidFinder.call(myEmployees);
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=192588