defcalculator():
result =0defadd(x):nonlocal result
result += x
return result
defminus(x):nonlocal result
result -= x
return result
deftimes(x):nonlocal result
result *= x
return result
defdivide(x):nonlocal result
result =int(result / x)return result
keys =('add','minus','times','divide')
functions =(add, minus, times, divide)
tuple_list =list(zip(keys, functions))returndict(tuple_list)
c1 = calculator()print(c1['add'](10))//10print(c1['times'](15))//150print(c1['divide'](3))//50print(c1['minus'](2))//48
c2 = calculator()print(c2['add'](3))//3
java
publicclassClosure4Java{privatestaticMap<String,Function<Integer,Integer>>createCalculator(){// 使用包含可变状态的对象模拟闭包classMutableResult{privateint result =0;}MutableResult mutableResult =newMutableResult();// 定义四个操作函数,并将其添加到映射中Map<String,Function<Integer,Integer>> operations =newHashMap<>();
operations.put("add", x ->{
mutableResult.result += x;return mutableResult.result;});
operations.put("minus", x ->{
mutableResult.result -= x;return mutableResult.result;});
operations.put("times", x ->{
mutableResult.result *= x;return mutableResult.result;});
operations.put("divide", x ->{
mutableResult.result /= x;return mutableResult.result;});return operations;}publicstaticvoidmain(String[] args){Map<String,Function<Integer,Integer>> c1 =createCalculator();System.out.println(c1.get("add").apply(3));// 3System.out.println(c1.get("times").apply(7));//21System.out.println(c1.get("divide").apply(2));//10Map<String,Function<Integer,Integer>> c2 =createCalculator();System.out.println(c2.get("add").apply(4));//4}}
groovy-script
defcalculator(){def result =0def add ={ x ->
result += x
result
}def minus ={ x ->
result -= x
result
}def times ={ x ->
result *= x
result
}def divide ={ x ->
result /= x
result
}// 创建包含闭包的映射def operations =['add': add,'minus': minus,'times': times,'divide': divide
]return operations
}// 使用闭包计算器def c1 =calculator()
println c1['add'](5)// 输出: 5
println c1['minus'](3)// 输出: 2
println c1['times'](4)// 输出: 8
println c1['divide'](2)// 输出: 4def c2 =calculator()
println c2['add'](3)// 输出: 3
groovy-class
classClosure4Groovy2{staticclassCalculator{privateint result =0def add ={ x ->
result += x
result
}def minus ={ x ->
result -= x
result
}def times ={ x ->
result *= x
result
}def divide ={ x ->
result /= x
result
}defgetOperations(){['add': add,'minus': minus,'times': times,'divide': divide
]}}staticvoidmain(String[] args){// 使用闭包计算器def c1 =newCalculator()def operations = c1.getOperations()
println operations['add'](5)// 输出: 5
println operations['minus'](3)// 输出: 2
println operations['times'](4)// 输出: 8
println operations['divide'](2)// 输出: 4}}