Python closure sample

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.

For Python (3.X)

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

For Scheme

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

Python closure sample
Python> function> Closure
Ajax + Python + PostgreSQL sample
Python --Simple multi-thread sample
Sample data created with python
Python
GitHub Actions Python cache sample
Python higher-order function (decorator) sample
Sample usage of Python pickle
closure
[Python] Sample code for Python grammar
AtCoder: Python: Daddy the sample test.
[Introduction to Udemy Python 3 + Application] 56. Closure
[Python] Test sample using unittest2, mock
My favorite boto3 (Python) API sample
Python parallel / parallel processing sample code summary
NAOqi Python sample (make NAO walk)
kafka python
Google Cloud Vision API sample for python
Python Summary
Built-in python
Python comprehension
Python technique
Studying python
Python 2.7 Countdown
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
Python memo
ufo-> python (3)
Closure 4 language comparison (Python, JavaScript, Java, C ++)
Python comprehension
install python
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
atCoder 173 Python
PHP / Python / Ruby sample hitting Path API
[Python] function
PyAudio sample
Closure implementation
Python installation
python tips
Sample script to trap signals in Python
Installing Python 3.4.3.
Python memo
Python iterative
Python algorithm
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
Start python