Examples of familiar closures + higher-order functions in Scheme (counter, [Wikipedia's "closures"](https://ja.wikipedia.org/wiki/%E3%82%AF%E3%83%AD%E3%83% BC% E3% 82% B8% E3% 83% A3)) rewritten in Python is described as a memorandum.
The point is, if you want to rewrite the value of the included external variable in the function body, is it necessary to declare it as 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
Check the execution at 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
Recommended Posts