Dodo doc > Macros and Templates > Templates > Type Template


Type Template

A type template is a generic model of a type that can be applied to a particular set of parameters to give a new, concrete type.

Declaration

The syntax borrows from the type declaration syntax, but keyword "template" followed by a list of parameters is added in front of it. Each parameter consists of a key and a colon followed by the parameter name with a "$" in front. In addition, constraints on the parameters can be specified in a [where] clause after the parameter list.

Advantages
Parameters can be types
Allows to specify constraints on parameters
Inconvenients
The type must be applied to be a concrete type

Example:

template (window: $Window) [where Window ~ HouseWindow]
class House
{
   Window[] windows
   ...
}
Rationale: this syntax ties well with other parts of the language. The key-colon-pattern syntax is used elsewhere, and [where] is also used to filter a list. The combination allows to express many forms of type templates.

Definition

The type definition also uses the "template" keyword and the parameters must be repeated. The parameter name in the type definition does not have to match the declaration. The constraints do not have to be repeated.

The constraints can also be more restrictive; in that case, the definition only applies when parameters satisfy the constraints. This allows to define different implementations depending on the value of parameters. The last definition to match wins.

Example:

template (window: $DW) [where DW ~ DoubleGlazedWindow] class House
{
   ...
}
template (window: $SW) [where SW ~ SingleGlazedWindow] class House
{
   ...
}
Rationale: generally, a variable declared in a pattern is valid only in the following block so it is necessary to repeat the parameter list. The parameter name does not matter as long as it is consistent throughout the definition. The order of precedence means that a catch-all implementation can be written first and specific implementations can be provided afterwards for some parameter values.

Use

A type template can be used as prototype for a concrete type or a new type template. The syntax is the same as other prototype uses.

Example:

def RoundWindowHouse = new House(window: RoundWindow)

It can also be used in a type position in a variable declaration by enclosing the parameters in angled brackets.

Example:

House(<window: RoundWindow>) funkyHouse

The type template can also be used in a function definition in a more generic way, without parameters. That makes the function using it generic too.

Rationale: the syntax mirrors that of a type with attributes, keeping the language coherent and reducing the learning curve. Generic functions are usually typed by their parameters so it is a small leap to propagate the genericity to a function with a generic type as parameter.

^ 5.4.2. Type With Abstract State

v 5.4.4. Method Template