Accumulator GeneratorPosted: December 13, 2007
I just came across this PG’s page:
Revenge of the Nerds yielded a collection of canonical solutions to the same problem in a number of languages.
The problem: Write a function foo that takes a number n and returns a function that takes a number i, and returns n incremented by i.
Note: (a) that’s number, not integer, (b) that’s incremented by, not plus.
For python he offers this approach:
class foo: def __init__(self, n): self.n = n def __call__(self, i): self.n += i return self.n
I thought of it for a few seconds and realized that this class instantiation is not necessary. Same can be achieved this way:
def foo(n): def _inci(n, x): n+=x return n return lambda i: _inci (n,i)Advertisements