accumulators

Paul Rubin http
Sat Jun 12 12:55:57 EDT 2004


Eugene Van den Bulke <eugene at boardkulture.com> writes:
> It seems to me that this code does the job (but I am not sure I
> understand exactly what an accumulator is):
> 
> def test(n):
> 	return lambda i: n+i
> 
> Is that an accumulator? If it is, PG must have written this chapter
> working on an older verion of Python ...

No.  The idea of an accumulator is that whenever you call it, the
internal state updates.  That is, if accum(n) creates an accumulator,
you should be able to say:

   a = accum(3)    # create accumulator holding 3
   print accum(2)  # prints "5"
   print accum(3)  # prints "8"
   print accum(1)  # prints "9"

etc.  The Pythonic way to do it is with a class instance:

  class accum:
    def __init__(self, n):
       self.s = n
    def __call__(self, i):
       self.s += i
       return self.s

  a = accum(3)
  (etc.)

however, for programmers comfortable with the Lisp idioms of using
internal lambdas, the class/object approach is cumbersome.



More information about the Python-list mailing list