Movatterモバイル変換
[0]ホーム
[Python-Dev] PEP 342: simple example, closure alternative
Andrew Koenigark at acm.org
Fri Aug 26 05:18:43 CEST 2005
> 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 += incrMaybe 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] += incrreturn acc[0]return fHere, the [0] turns "read-only" access into write access to a list element.The list itself isn't written; only its element is.
More information about the Python-Devmailing list
[8]ページ先頭