Accumulator Generator

I just came across this PG’s page:

Accumulator Generator

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):
        return n

    return lambda i: _inci (n,i)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s