Dodo doc > Macros and Templates > Templates > Function Template


Function Template

Declaration

A function template declaration starts with the keyword "template" followed by template parameters. There can be a [where] clause after the type parameters to add parameter constraints. Then the function declaration comes.

Example:

template (type: $Coord, distance: $Distance) [where Coord ~ Arithmetic]
def distanceFromOrigin(Coord, Coord) -> Distance
Rationale: The template syntax is same as in type or method declaration.

Definition

The definition repeats the template parameters from the function template declaration. It is optional to repeat the constraints.

The constraints can be more restrictive than the declaration, which allows to define different function bodies depending on template parameters. In that case the last function template to match wins.

In the body only operations defined in types which match the constraints can be used.

Example:

template (type: $Coord, distance: $Distance)
def distanceFromOrigin(Coord x, y) -> return(Distance)
{
   return (x **2 + y **2) **0.5
}
Rationale: the template parameters are declared using patterns, which means they are only valid in the following expression. So they need to be declared again in the function template definition. Specialised bodies allow to optimise a function algorithm. A more generic body can be defined first for other cases thanks to the last match rule. The template can only be applied if the operations used are compatible with the parameters, which the compiler will detect.

Use

When using a function template with a generic function parameter, the type of this parameter is determined by the argument passed to the function. If the return value is generic its type is determined by the continuation that uses that value, for example a variable assignment.

Example:

double d = distanceFromOrigin(30, -5.5)  # Distance is type double

The function template can be used as prototype for a new function or made into a concrete function by using the angle brackets syntax.

Rationale: in case of a function the compiler knows enough about the types to convert a function template into a concrete function without setting the template parameters explicitly. When the template parameters are given, the result is a concrete function which can be used as prototype.

^ 5.4.4. Method Template

v 6. Expressions and Instructions