Closures
Today: Scopes
Where are we now?
What is a Closure?
f = lambda x, y : x + y
var f = function(x, y) {
return x + y;
}
var f = (x, y) => {
return x + y;
}
auto f = [](int x, int y) {
return x + y;
};
BinaryOperator<int> f = (int x, int y) -> {
return x + y;
};
Python
C++
Java
Javascript
What is a Closure?
var f = fun(x) {
print(x);
};
f(1)
var x = 1;
var f = fun() {
print(x);
};
f();
Output: 1
var x = 1;
var f = fun() {
x = 2;
};
print(x)
var g = fun(h) {
h();
}
print(x)
g(f);
print(x);
Output: 1
Outputs: �1�1�2
Why?
Callbacks
Anonymous helper functions
What is a Closure?
var f = fun(x) {
print(x);
};
f(1)
var x = 1;
var f = fun() {
print(x);
};
f();
Output: 1
var x = 1;
var f = fun() {
x = 2;
};
print(x)
var g = fun(h) {
h();
}
print(x)
g(f);
print(x);
Output: 1
Outputs: �1�1�2
Scoping
class Test
{
void foo()
{
int x = 1;
int y = x;
}
}
...
y = x;
...
class Test
{
void foo(int x)
{
int y = x;
}
}
class Test
{
void foo(int x, int y)
{
{
int y = x;
}
print(y);
}
}
Scoping
class Test
{
static int y = 1;
void foo(int x)
{
y = x;
}
}
class Test
{
int y = 1;
void foo(int x)
{
y = x;
}
}
Block Scopes for IMP (MITScript is different)
var x = 1;
{
var x = 2;
print(x);
}
print(x)
var x = 1;
{
x = 2;
print(x);
}
print(x)
output:
2
1
output:
2
2
Scoped For Loop Translation
{
int i = 0;
while (i < n) {
...
++i;
}
}
{
i = 0;
while (i < n) {
...
++i;
}
}
for (int i = 0; i < n; ++i) {
...
}
for (i = 0; i < n; ++i) {
...
}
Add Block Scopes: Grammar
Add Block Scopes: Grammar
Block Scopes: Semantic Meaning
var x = 1;
{
var x = 2;
print(x);
}
print(x)
var x = 1;
{
x = 2;
print(x);
}
print(x)
Add x = 1 to scope
Modify x in scope
Add x = 1 to scope
Add x = 2 to scope
Frames, Heaps, and Stacks
Evaluation Relations (old)
Evaluation Relations (with heaps and stacks)
Statements: Inference Rules
Expressions: Inference Rules
Integer
Constant
Variable
Reference
Unary
Minus
Lookup
Expressions: Inference Rules
Integer
Constant
Variable
Reference
Unary
Minus
Statements: Inference Rules
{
var x = 1;
var x = 2;
}
Statements: Inference Rules
Update
Managing Scopes (Example)
1: var f = 0;
2: {
3: var x = 1;
4: f = 5;
5: }
Line | | Heap (h) |
1 | | { 100 : 0 } |
2 | | { 100 : 0 } |
3 | | { 100 : 0, 101 : 1 } |
4 | | { 100 : 0, 101 : 1, 102 : 5 } |
5 | | { 100 : 0, 101 : 1, 102 : 5 } |