Help us understand the problem. What is going on with this article?

Pythonのクロージャのサンプル

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
ytaki0801
``Don't feel as if the key to successful computing is only in your hands.'' -- Alan J. Perlis
http://nbk.bz/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away