Closures
Planned Features
Anonymous Functions
Create functions without naming them:
let add: function(i32, i32): i32 = (a: i32, b: i32): i32 => { return a + b;};
let result: i32 = add(5, 3); // 8Short Syntax
Single-expression functions with implicit return:
let double: function(i32): i32 = (x: i32): i32 => x * 2;let square: function(i32): i32 = (x: i32): i32 => x * x;Capturing Variables
Closures can capture variables from their surrounding scope:
function makeCounter(): function(): i32 { let count: i32 = 0;
return (): i32 => { count = count + 1; return count; };}
function main(): i32 { let counter: function(): i32 = makeCounter();
let a: i32 = counter(); // 1 let b: i32 = counter(); // 2 let c: i32 = counter(); // 3
return c;}Higher-Order Functions
Pass functions as arguments:
function map(arr: i32[], length: i32, fn: function(i32): i32): i32[] { let result: i32[] = new i32[]; let i: i32 = 0;
while (i < length) { result.push(fn(arr.get(i))); i = i + 1; }
return result;}
function main(): i32 { let numbers: i32[] = new i32[]; numbers.push(1); numbers.push(2); numbers.push(3);
let doubled: i32[] = map(numbers, 3, (x: i32): i32 => x * 2); // doubled = [2, 4, 6]
return doubled.get(0);}Callbacks
Use closures for event handling and callbacks:
function processAsync(callback: function(i32): void): void { let result: i32 = 42; callback(result);}
function main(): i32 { let received: i32 = 0;
processAsync((value: i32): void => { received = value; });
return received;}Use Cases
Functional Patterns
// Filterfunction filter(arr: i32[], length: i32, predicate: function(i32): boolean): i32[] { let result: i32[] = new i32[]; let i: i32 = 0;
while (i < length) { if (predicate(arr.get(i))) { result.push(arr.get(i)); } i = i + 1; }
return result;}
// Usagelet evens: i32[] = filter(numbers, 5, (x: i32): boolean => x % 2 == 0);Deferred Execution
function lazy(computation: function(): i32): function(): i32 { let cached: i32 = 0; let computed: boolean = false;
return (): i32 => { if (!computed) { cached = computation(); computed = true; } return cached; };}Current Workaround
Until closures are available, use classes to capture state:
class Counter { private count: i32;
constructor() { this.count = 0; }
public increment(): i32 { this.count = this.count + 1; return this.count; }}Roadmap
| Feature | Status |
|---|---|
| Anonymous functions | Planned |
| Arrow syntax | Planned |
| Variable capture | Planned |
| Higher-order functions | Planned |
Follow development on GitHub!