v3 Language: Collections and Closures
Lesson, slides, and applied problem sets.
View SlidesLesson
v3 Language: Closures, Arrays, Maps
Why this module exists
We now cross the line into "real" language territory:
- nested functions with lexical scoping
- arrays and maps as heap objects
- indexed reads and writes
- runtime GC to manage memory
This is a different level of complexity, and that's the point.
1) Arrays and maps
Array literal:
let xs = [1, 2, 3];
Map literal (expression context):
let m = {"a": 1, "b": 2};
Map keys must be hashable: number, bool, string, or nil. Other key types are runtime errors.
2) Indexing and assignment
Read:
let v = xs[0];
Write:
xs[1] = 42;
m["a"] = 99;
Index assignment is a statement in this pack.
3) Nested functions + lexical scoping
Functions can appear inside blocks and return other functions:
fn makeAdder(x) {
fn add(y) { return x + y; }
return add;
}
The inner function captures x from its defining scope. This is lexical scoping.
4) Functions are values
Calls are allowed on any expression, not just identifiers:
let f = makeAdder(10);
let z = f(2);
5) Memory is real now
Arrays, maps, and closures live on a heap. The VM will use mark-and-sweep GC to reclaim unreachable objects.