func adder() func (value int){ sum := 0 return func(value int) int{ sum += value return sum } } func main() { adder := adder() for i := 0; i < 10; i++ { fmt.Println(adder(i)) } }
函數式編程 VS 函數指針java
type iAdder func(int) (int, iAdder) func adder(base int) iAdder { return func(value int) (int, iAdder){ return base+value, adder(base+value) } } func main(){ a := adder(0) for i := 0; i < 10; i++ { fmt.Println(a(i)) } }
def adder(): sum = 0 def f(value): nonlocal sum sum += value return sum return f
auto adder() { auto sum = 0; return [=] (int value) mutable { sum += value; return sum; }; }
Function<Integer, Integer> adder() { final Holder<Integer> sum = new Holder<>(0); return (Integer value )-> { sum.value += value; return sum.value; }; }