원클릭으로
capture-state-closure
// For persistent state: closures capture outer variables, alternative to classes for simple state, factory functions that remember context.
// For persistent state: closures capture outer variables, alternative to classes for simple state, factory functions that remember context.
| name | capture-state-closure |
| description | For persistent state: closures capture outer variables, alternative to classes for simple state, factory functions that remember context. |
Nested function captures variables from enclosing scope.
def make_counter(start=0):
"""Create a counter function with persistent state."""
count = start # Captured by inner function
def counter():
nonlocal count
count += 1
return count
return counter
c = make_counter(10)
c() # 11
c() # 12
# Memoization via closure (ngrams.py)
def memo(f):
"""Memoize function f."""
table = {} # Captured mutable state
def fmemo(*args):
if args not in table:
table[args] = f(*args)
return table[args]
fmemo.memo = table # Expose cache for inspection
return fmemo
@memo
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
# Access the cache
fibonacci.memo # {(0,): 0, (1,): 1, (2,): 1, ...}
# Symbol interning (lispy.py)
def Sym(s, symbol_table={}): # Mutable default = persistent state
"""Find or create unique Symbol for string s."""
if s not in symbol_table:
symbol_table[s] = Symbol(s)
return symbol_table[s]
# Same symbol every time
assert Sym('quote') is Sym('quote')
# Partial application via closure
def make_multiplier(factor):
"""Create a function that multiplies by factor."""
def multiply(x):
return x * factor # factor captured
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
double(5) # 10
triple(5) # 15
Conducts iterative deep research on any topic using web search, progressive exploration, and structured synthesis. Use when asked for comprehensive research, deep investigation, thorough analysis, or multi-source exploration of any topic. Triggers: research, investigate, deep dive, comprehensive analysis, explore thoroughly, find everything about.
For cross-cutting concerns: add behavior without modifying functions, caching, timing, logging, validation wrappers.
For performance work: measure before changing, profile to find bottlenecks, compare before and after.
For symbolic computation: ASTs, mathematical expressions, code that manipulates code structure, expression transformations.
For ordered processing: A* search, Dijkstra, event simulation, task scheduling. Efficient min/max extraction with heap-based queue.
For dynamic programming: overlapping subproblems, recursive solutions with repeated computations, memoization to avoid redundant work.