# <span class="fa-stack"><i class="fa-solid fa-circle fa-stack-2x"></i><i class="fa-solid fa-book fa-stack-1x fa-inverse"></i></span> Nested Functions - Function `f()` has free variable `x` - :fa fa-question-circle: To which `x` should we bind the free `x` in `f`? <div class="grid grid-cols-2 gap-4"> <div> ```scala val x = 4 def f() = x+1 def g() = val x = 7 f() end g g() ``` * Using our simple language semantics: binds `x` in `f` to `x` in line 4 (returns $8$ instead of $5$) </div> <div> - Simple language semantics does not capture values of variables $$\frac{}{\langle \mathtt{def\ f = e},\xi,\phi \rangle \Downarrow \langle 0,\xi,\phi\{\mathtt{f} \mapsto \mathtt{e}\} \rangle}\text{\tiny(FunDef)}$$ - Simply consults the global store at the time of function application $$\frac{\phi(\mathtt{f})=\mathtt{e} \qquad \langle \mathtt{e},\xi,\phi\rangle \Downarrow \langle v,\xi',\phi' \rangle}{\langle \mathtt{f()},\xi,\phi \rangle \Downarrow \langle v,\xi',\phi' \rangle}\text{\tiny(FunApp)}$$ </div> </div> ---
# <span class="fa-stack"><i class="fa-solid fa-circle fa-stack-2x"></i><i class="fa-solid fa-book fa-stack-1x fa-inverse"></i></span> Nested Functions: GCC - Lifetime problems caused by nested functions <div class="grid grid-cols-2 gap-4"> <div> ```c typedef void (*funcptr) (int); funcptr f (int x) { void g (int y) { printf ("x = %d, y = %d\n", x, y); } g (1); return &g; } int main (void) { funcptr h = f (10); (*h) (2); f (20); (*h) (3); } ``` </div> <div> Unsafe calls may or may not work ```sh $ gcc -std=c99 nested-gcc.c $ ./a.out x = 10, y = 1 <- g(1): safe to call g, with x=10 x = 10, y = 2 <- (*h)(2): unsafe to call h, created with x=10 x = 20, y = 1 <- g(1): safe to call g x = 20, y = 3 <- (*h)(3): unsafe to call h, created with x=10 ``` </div> </div> ---
# <span class="fa-stack"><i class="fa-solid fa-circle fa-stack-2x"></i><i class="fa-solid fa-book fa-stack-1x fa-inverse"></i></span> Nested Function: Java With explicit object instantiation <div class="text-xl"> ```java import java.util.function.Function; static Function<Integer,Void> f (int x) { Function<Integer,Void> g = new Function<Integer,Void>() { public Void apply(Integer y) { System.out.format ("x = %d, y = %d%n", x, y); return null; } }; g.apply (1); return g; } public static void main (String[] args) { Function<Integer,Void> h = f (10); h.apply (2); f (20); h.apply (3); } ``` </div> ---