Function definition
A function is a typed, reusable unit of model logic. Like a Template, it packages calculation rules so the same logic can be applied to different arguments. Unlike a template, a function declares the value type and domain of every parameter and of its result, and is type-checked once, at its definition — not re-checked separately at each call site.
Because a function has a declared result type, an application F(args) is an expression of that type, and so it nests inside larger expressions like any operator or function call.
parameters — a typed telescope
The parameters follow the function name in parentheses, separated by semicolons. Each is an ordinary typed declaration, and together they form a telescope: a later parameter may refer to an earlier one. A domain parameter is a unit; an attribute parameter names its domain in parentheses.
function CongestionRatio(
unit<uint32> Rd;
attribute<float64> flow (Rd);
attribute<float64> cap (Rd))
Here flow and cap are attributes over the unit Rd, which is itself a parameter. The argument list at the call is matched against this telescope by position, and its length (arity) is checked at the call.
Declarations may also be written in name: type style, and several names may share a single type and calculation rule:
Rd: unit<uint32>;
c1, c2: parameter<float64> := 1.0;
Every name of such a declaration also gets its data block, its properties and its nrofrows: after a, b: attribute<int32> (D) : [1, 2, 3]; both a and b hold the three values.
the result — after ->
The result specification follows ->. It gives an optional result name, the result type, and — after := — a result expression that relates the result to the body:
-> attribute<float64> (Rd) := min_elem(raw, 1.0);
If a name is given it precedes the type; otherwise the synthesised result item is named result:
-> link_counts: attribute<uint32> (nw/nodeset) := pcount(nw/F1) + pcount(nw/F2);
the body and the three forms
A function may carry an optional body block in braces, holding intermediate items. How the result expression relates to that body gives three forms.
Form a — the result expression is a plain name designating a body item (matched case-exactly, else case-insensitively-unique):
function CongestionRatio3(
Rd: unit<uint32> { flow: attribute<float64>; cap: attribute<float64>; })
-> attribute<float64> (Rd) := Result
{
attribute<float64> raw (Rd) := Rd/flow / Rd/cap;
attribute<float64> result (Rd) := min_elem(raw, 1.0);
}
Form b — the result expression is the calculation rule of the result, written over body items:
function CongestionRatio(
unit<uint32> Rd; attribute<float64> flow (Rd); attribute<float64> cap (Rd))
-> attribute<float64> (Rd) := min_elem(raw, 1.0);
{
attribute<float64> raw (Rd) := flow / cap;
}
Form c — expression-only, with no body block at all:
function CongestionRatio2(
unit<uint32> Rd { attribute<float64> flow; attribute<float64> cap; })
-> attribute<float64> (Rd) := min_elem(Rd/flow / Rd/cap, 1.0);
subitems of a typed result
Direct subitems declared beneath a typed result body item are retained when the function is applied. This allows a function to return a fresh domain together with its relations or other attributes:
function sorted_domain<V: any, D: domains>(attribute<V> value (D))
-> unit<D> := result
{
attribute<D> permutation (D) := index(value);
unit<D> result := unique(permutation)
{
attribute<D> org_rel := lookup(result/values, permutation);
}
}
The caller receives both the fresh unit and org_rel:
unit<uint32> Sorted := sorted_domain(Source/value);
attribute<uint32> original_row (Sorted) := Sorted/org_rel;
This remains a value-returning function application: only the result item and its subitems are materialized. Other intermediate body items are still retained only by instantiate.
The same holds inside a body. A body item that is the result of another function has the subitems that the function declares for its result, a body item defined by Fold those that its step declares, and the body refers to them by path:
function DropMax(parameter<uint32> e; unit<uint32> s { attribute<float64> v; }) -> unit<uint32> := kept
{
unit<uint32> kept := select_with_org_rel(s/v < max(s/v))
{
attribute<float64> v := s/v[kept/org_rel];
}
}
function SumAfterDrop(unit<uint32> s { attribute<float64> v; }) -> parameter<float64> := sum(h/v)
{
unit<uint32> h := DropMax(0u, s);
}
Here h/v is the attribute v that DropMax declares beneath its result kept. The subitems that the operator of that result makes itself, such as the org_rel of select_with_org_rel, are there as well. A path to a subitem that is in neither is an error that names the body item, the function and the subitems that are declared; with h/w in SumAfterDrop it reads ‘h/w’: Cannot find ‘w’ from ‘/SumAfterDrop/h’, a body item of function ‘/SumAfterDrop’; the function or fold whose result it is declares ‘v’.
A body item defined as instantiate G(args) is a copy of the function G with those arguments. In a copy of F made with instantiate F(args) it is a container with the items of G. In a function that is applied as a value, the body refers to the items of the copy by their path, as it would to the items of that container:
function G(unit<uint32> s { attribute<float64> v; }) -> parameter<float64> := total
{
parameter<float64> total := sum(s/v);
unit<uint32> kept := select_with_org_rel(s/v < max(s/v))
{
attribute<float64> v := s/v[kept/org_rel];
}
}
function F(unit<uint32> s { attribute<float64> v; }) -> parameter<float64> := c/total + sum(c/kept/v)
{
container c := instantiate G(s);
}
A path can lead to a body item of G, as c/total, to a subitem of one, as c/kept/v, to a parameter of G, as c/s/v, which is the argument that the copy was made with, and through a copy that G itself makes, as c/inner/total. A function defined inside F refers to them in the same way. Applying F makes no items: of the items of G, only the ones that the body refers to are calculated, with the arguments of the copy, so an item of G that nothing refers to costs nothing, also when calculating it would fail. The copy itself has no value: c + 1.0, or c as the result of F, is an error that names an item of G to refer to instead, and a path to an item that G does not have is an error that lists the items it does have. A function that G defines serves the items of G: an item of G may apply it, and F may refer to that item, but F cannot apply the function through the copy, as c/Plus(1.0).
structured unit parameters
A unit parameter may carry a member block declaring the attributes the argument table must supply. This is a declared interface only: the body reaches the members through the parameter, as Rd/flow.
unit<uint32> Rd {
attribute<float64> flow;
attribute<float64> cap;
}
At the call the parameter binds by reference to the actual argument — the argument’s data is not copied.
scope — lexical from the definition site
Identifiers in a function’s expressions resolve to what is visible at the point of definition, as everywhere else in the language. A body sees, in order:
- the function’s parameters,
- its own body items (nearest enclosing body scope first),
- containers explicitly imported with a
usingclause, - the surrounding namespace of the definition — the definition parent and its ancestors, with their
usingdirectives — exactly as any ordinary calculation rule written at that spot would see them, - the auto-imported prelude of standard function definitions, as implicit outermost namespace.
So a unit, parameter or sibling function declared next to the function is simply visible in its body, without any import:
parameter<float64> outside := 42.0;
function F(unit<uint32> Rd; attribute<float64> x (Rd))
-> attribute<float64> (Rd) := x * outside;
A function defined in the body of another function also sees the parameters and the body items of that enclosing function, with their subitems. When the enclosing function is applied as a value, these are its arguments and the body items that it calculates. In the example below, DropMax from above is the step of a Fold over Twice, a unit of two elements, and the inner function reads the state st that the fold yields, and its subitem st/v. A path such as s/v to a parameter of the enclosing function works the same way.
function OuterFold(unit<uint32> s { attribute<float64> v; }) -> parameter<float64> := Inner(1.0)
{
unit<uint32> st := fold(Twice, DropMax, s);
function Inner(parameter<float64> k) -> parameter<float64> := sum(st/v) + k;
}
With the values 5, 3, 8, 1 and 4 for s/v, the fold drops the two largest values, and OuterFold gives 3 + 1 + 4 + 1 = 9.
What a function never sees is the call site. The only channel from the caller is the argument list, and argument expressions are resolved in the caller’s scope. This call-site isolation is the crucial difference from a Template, whose instantiated body also keeps names at the instantiation point reachable as a fallback.
the using import clause
A using clause after the parameter list imports additional containers into the function’s scope; its paths are resolved at the definition site.
function Capped(
unit<uint32> Rd;
attribute<float64> x (Rd))
, using = shared
-> attribute<float64> (Rd) := min_elem(x, limit);
Here limit is found in the imported container shared.
meta-reference parameters
A parameter declared with the item keyword is a meta-reference parameter: its argument binds as a raw item reference rather than as a computed value, so the body can read the argument item’s own metadata. The built-in property accessors are defined this way:
function name(item t) -> parameter<string> := PropValue(t, 'name');
applying a function
An application F(args) is an expression of the result type, and calls compose freely — a function may apply another in its result expression, and a top-level item may apply that function in turn:
function F(unit<uint32> Rd; attribute<float64> x (Rd)) -> attribute<float64> (Rd) := 2.0 * x;
function useF(unit<uint32> U; attribute<float64> y (U)) -> attribute<float64> (U) := F(U, y);
attribute<float64> c (Road) := useF(Road, Road/flow);
Where a function has a body block whose intermediate items you want to keep, instantiate lands the whole body as a container and you reach the result through it:
container cr := instantiate CongestionRatio(Road, Road/flow, Road/cap);
attribute<float64> congestion (Road) := cr/result;
repeating a step
A function body holds a fixed set of items, which the definition check sees. When the function is applied as a value, in an expression F(args), its body therefore cannot contain a meta function such as For_each, Loop or iterate, which makes items from its arguments, nor an Indirect expression: GeoDMS refuses them with ‘for_each_nedv’: meta function call is not supported inside function bodies when the function is applied in an expression and leading-‘=’ string indirection is not supported inside function bodies. The message of a meta function call goes on with what can be done instead:
- When an argument of the call depends on a parameter of the function, the message names the argument and the parameter, as Argument 3 of for_each_nedv depends on the parameter ‘dom’. Such a call can then only be made in a copy of the function made with
instantiate F(args), the third point below. In a function defined inside another function, an argument can also depend on a parameter or a body item of the enclosing function, which the message names with that function. - When no argument depends on a parameter, the call makes the same items each time the function is applied. Move it into the container that holds the function, which the message names, and refer to the items it makes from the body.
- A copy of the function made with
container c := instantiate F(args)accepts the call, as an instance of a Template does, and the items that the call makes are in that copy. - For Loop and iterate, the message points at Fold and Fold_c, which repeat a step inside a function body, as below.
To repeat a step, write Fold. fold(D, step, x0) applies the function step once for each element of the unit D, each time to the state that the application before it returned, starting from x0, and yields the state that the last application returns. D may be a parameter, so the number of repetitions can be an argument of the function:
function Halve(unit<uint32> dom; parameter<uint32> i; attribute<float64> x (dom)) -> attribute<float64> (dom) := x * 0.5;
function HalveN(unit<uint32> dom; unit<uint32> iterations; attribute<float64> x (dom)) -> attribute<float64> (dom) := fold(iterations, Halve(dom, _, _), x);
unit<uint32> iter := range(uint32, 0, nrIterations);
attribute<float64> result (R) := HalveN(R, iter, R/v);
To repeat a step until a condition fails, write Fold_c: fold_c(step, condition, maxN, x0) applies step for as long as condition is true for the state, at most maxN times. A body may also hold container trace := instantiate fold(...), whose items, one per step, appear in a copy of the function made with instantiate F(args).
The definition check types the step twice, first for the state x0 and then for the state that the step returns, so it finds a step whose result does not fit its own input without knowing how many elements D has. The convex hull example script repeats its step this way. The operators Loop and iterate repeat a Template.
function versus template
A Template and a function both package reusable model logic, but differ in what is checked and when.
| aspect | template | function |
|---|---|---|
| parameters | untyped; the “first N subitems”, matched by argument count | declared, named, typed telescope; arity checked at the call |
| checking | body checked per instantiation, at every call site | type-checked once, at the definition |
| composability | cannot be used as a sub-expression | F(args) is an expression of the result type, nestable |
| scope | definition scope first, with the instantiation site as fallback | lexical definition scope; the call site is never visible |
| For_each and Indirect expressions in the body | allowed: the body is worked out per instantiation | refused when the function is applied as a value, as the body is fixed at the definition; a copy made with instantiate F(args) accepts a meta function, and Fold and Fold_c repeat a step |
| result | some subitem, by convention; untyped | a typed, named result (default result) |
see also
- Template
- Function signature
- Type alias
- Generic function
- Anonymous function
- Closure
- Variadic parameters
- Map
- Fold
- Fold_c
- Operators and functions
since version
20.9.0; the subitems of a typed result since 20.18.0, and the data block, properties and nrofrows for every name of a declaration with several names since 20.24.0.