Python syntax in Lisp and Scheme
David Eppstein
eppstein at ics.uci.edu
Sat Oct 4 14:22:02 EDT 2003
In article <mailman.1065288850.20400.python-list at python.org>,
Lulu of the Lotus-Eaters <mertz at gnosis.cx> wrote:
> grzegorz at pithekos.net (Grzegorz Chrupala) wrote previously:
> |shocked at how awkward Paul Graham's "accumulator generator" snippet is
> |in Python:
> |class foo:
> | def __init__(self, n):
> | self.n = n
> | def __call__(self, i):
> | self.n += i
> | return self.n
>
> Me too. The way I'd do it is probably a lot closer to the way Schemers
> would do it:
>
> >>> def foo(i, accum=[0]):
> ... accum[0]+=i
> ... return accum[0]
> ...
> >>> foo(1)
> 1
> >>> foo(3)
> 4
>
> Shorter, and without an awkward class.
There's an important difference between these two: the object-based
solution (and the solutions with two nested functions and a closure)
allow more than one accumulator to be created. Yours only creates a
one-of-a-kind accumulator.
I happen to like the object-based solution better. It expresses more
clearly to me the intent of the code. I don't find the class awkward;
to me, a class is what you use when you want to keep some state around,
which is exactly the situation here. "Explicit is better than
implicit." Conciseness is not always a virtue.
--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
More information about the Python-list
mailing list