Closure ?
メモ
Ruby
Python 2.x
Python 3.x
ちなみに、ジェネレータのおまけ
Ruby
def f
i = 0
return lambda {
i += 1
}
end
x = f
puts x.call()
puts x.call()
puts x.call()
Python 2.x
def f():
i = [0]
def g():
i[0] += 1
return i[0]
return g
x = f()
print x()
print x()
print x()
Python 3.x
def f():
i = 0
def g():
nonlocal i
i += 1
return i
return g
x = f()
print(x())
print(x())
print(x())
ちなみに、ジェネレータのおまけ
def f():
i = 0
while True:
i += 1
yield i
g = f()
print g.next()
print g.next()
print g.next()