\[ \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 provided
  • recurse is a name, so we recurse -> return, fact and n, all provided

Algorithm: \(\algo{closure}\). Given a name \(n\), and set of declarations \(\set D\). Returns a set of variables closed over in \(n\).

  1. Initialize a set of provided values \(\set P\).
  2. Retrieve the declaration \(n\ p_1\ p_2 \dots p_n: c\ a_1\ a_2 \dots a_m\).
  3. Insert \(p_1\ p_2 \dots p_n\) in \(\set P\).
  4. Foreach \(x \in \setp{c\ a_1\ a_2 \dots a_m}\):
    1. Retrieve \(x\) from \(\set D\).
    2. If \(x\) is a name:
      1. Compute \(\set X = \algo{closure}(x)\).
      2. For each \(x' in \set X\):
        1. If \(x' \notin \set P\), add \(x'\) to result set.
    3. If \(x\) is a parameter:
      1. Add \(x\) to the result set.