Closures
\[ \newcommand{algo}[1]{\mathrm{#1}} \newcommand{set}[1]{\mathcal{#1}} \newcommand{setp}[1]{\left\{ {#1} \right\}} \]
Closure
fact n return: isZero n base recurse
base: return 1
recurse: sub n 1 step1
step1 m: fact m step2
step2 f: mul n f return
fact
. Consider fact
, n
and return
provided. Iterate through call:
isZero
constant.n
is provided.base
is a name, so we recurse ->return
, which is providedrecurse
is a name, so we recurse ->return
,fact
andn
, all provided
Algorithm: \(\algo{closure}\). Given a name \(n\), and set of declarations \(\set D\). Returns a set of variables closed over in \(n\).
- Initialize a set of provided values \(\set P\).
- Retrieve the declaration \(n\ p_1\ p_2 \dots p_n: c\ a_1\ a_2 \dots a_m\).
- Insert \(p_1\ p_2 \dots p_n\) in \(\set P\).
- Foreach \(x \in \setp{c\ a_1\ a_2 \dots a_m}\):
- Retrieve \(x\) from \(\set D\).
- If \(x\) is a name:
- Compute \(\set X = \algo{closure}(x)\).
- For each \(x' in \set X\):
- If \(x' \notin \set P\), add \(x'\) to result set.
- If \(x\) is a parameter:
- Add \(x\) to the result set.