Schemeではおなじみのクロージャ+高階関数の例(counter,Wikipediaの『クロージャ』を参照)をPythonで書き直したものを備忘録的に記載する.
Python(3.X)の場合
ポイントは,内包される外部変数の値を関数本体で書き換えたい場合は,nonlocalで宣言する必要があることだろうか.
counter.py
>>> def new_counter(c):
... def retfunc():
... nonlocal c
... c += 1
... return (c)
... return (retfunc)
...
>>> c1 = new_counter(10)
>>> c1()
11
>>> c1()
12
>>> c1()
13
Schemeの場合
実行はGaucheで確認.
counter.scm
gosh> (define new_counter
(lambda (c)
(lambda () (set! c (+ c 1)))))
new_counter
gosh> (define c1 (new_counter 10))
c1
gosh> (c1)
11
gosh> (c1)
12
gosh> (c1)
13