1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-07-16

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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?