# <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 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> ---
# <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> Closures: Problem Summary <div class="grid grid-cols-3 gap-4"> <div> ```scala def outer(x:A) : B=>C = def inner(y:B) : C = //...use x and y... end inner inner // return inner end outer val f = outer(...) f(...) ``` </div> <div class="col-span-2"> 1. Function `outer` is called - AR contains data `x` 2) Function `outer` returns nested function `inner` - Function `inner` has free variable `x` - ⇒ resolve with `x` from `outer`'s AR 3) Lifetime of `outer`'s AR and `x` ends 4) Nested function `inner` is called through alias `f` - Function `inner` needs `x` from `outer`'s AR </div> </div> * :fa fa-question-circle: Mutable vs. immutable state? ---
Closure for async Scala operation returning Future[]
Closure example in JavaScript: debounce