[Python-Dev] PEP 342: simple example, closure alternative
Ian Bicking
ianb at colorstudy.com
Fri Aug 26 06:59:42 CEST 2005
Andrew Koenig wrote:
>>A closure based accumulator (using Scheme):
>>
>>(define (accum n)
>> (lambda (incr)
>> (set! n (+ n incr))
>> n))
>>(define s (accum 0))
>>(s 1) ; -> 1 == 0+1
>>(s 5) ; -> 6 == 1+5
>>
>>So I thought the generator version might look like:
>>
>>def accum(n):
>> while 1:
>> incr = (yield n) or 0
>> n += incr
>
>
> Maybe I'm missing something but this example seems needlessly tricky to me.
> How about doing it this way?
>
> def accum(n):
> acc = [n]
> def f(incr):
> acc[0] += incr
> return acc[0]
> return f
>
> Here, the [0] turns "read-only" access into write access to a list element.
> The list itself isn't written; only its element is.
I was just exploring how it could be done with coroutines. But also
because using lists as pointers isn't that elegant, and isn't something
I'd encourage people do to coming from other languages (where closures
are used more heavily).
More generally, I've been doing some language comparisons, and I don't
like literal but non-idiomatic translations of programming patterns. So
I'm considering better ways to translate some of the same use cases.
--
Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org
More information about the Python-Dev
mailing list