Closures
Func literals, closure values, and routines and methods passed as values.
Examples: res\examples\language\closures holds small, commented programs for this page's features, each listing the output it prints; run one with adam build <file> -r.
Closure values
ref func(..) is a closure type: a value holding code and the variables it captured, nil until it is assigned; calling a nil closure raises. A func literal, func(..): T begin .. end, is a ref func of its own signature; its parameter types are written, never taken from where it goes.
module exe closures_basics;
type
Counter = ref func(): int64;
Transform = ref func(const AValue: int64): int64;
// A counter of its own: every call gives the next number
func MakeCounter(): Counter;
var
LCount: int64;
begin
LCount := 0;
return func(): int64
begin
LCount := LCount + 1;
return LCount;
end;
end;
// AFn applied to every value of AValues
func MapAll(const AValues: array of int64; const AFn: Transform): array of int64;
var
LOut: array of int64;
LI: int64;
begin
setlength(LOut, len(AValues));
for LI := 0 to len(AValues) - 1 do
LOut[LI] := AFn(AValues[LI]);
end;
return LOut;
end;
// Scales by a factor the literal captures
func Scaled(): array of int64;
var
LFactor: int64;
begin
LFactor := 10;
return MapAll([1, 2, 3], func(const AValue: int64): int64
begin
return AValue * LFactor;
end);
end;
var
GNext: Counter;
GOther: Counter;
GFirst: int64;
GSecond: int64;
GScaled: array of int64;
begin
GNext := MakeCounter();
GOther := MakeCounter();
GFirst := GNext();
GSecond := GNext();
println("{} {} {}", GFirst, GSecond, GOther());
GScaled := Scaled();
println("{} {} {}", GScaled[0], GScaled[1], GScaled[2]);
end.
1 2 1
10 20 30
Capture
A func literal captures by reference every local, parameter and self of its enclosing routine that it names: one set per call of that routine, shared by the routine and every closure the call made. That is why each counter above keeps its own count.
- A const parameter is captured by its value.
- A var parameter cannot be captured: the caller's variable may be gone before the closure runs.
- A module's variables are shared, never captured.
A func literal may declare its own var, const and type blocks, one set per call of it.
Routines and methods as values
A routine named as a value, another closure or nil can be stored in a ref func of the same shape. A method named as a value becomes a closure bound to its object, which must live in a ref or an own.
C callbacks
A func literal that captures nothing also fills a plain func(..) slot, such as a C callback; a capturing one reaches a C callback through CCallback<T>.