Skip to content

SpecificationIII · Types and values

3.12

Generics

A generic is a subroutine or a type written once for any type: the concrete type is filled in when it is used.

Markdown version

3.12.1 How it works

Sometimes the same idea works for many types: a box that holds a value, a subroutine that returns what it receives. With a type parameter, written between < and > after the name, a single version is written.

ProgramA subroutine for any type

Subroutine identidad<T>(valor As T) As T
  Return valor;
EndSubroutine
Algorithm Identidad
  Write identidad(4);
  Write identidad(2.5);
  Write identidad("hola");
EndAlgorithm

Output

4
2.5
hola

The program finishes normally.

The engine infers the type T in each call from the arguments. Records, classes, interfaces and variants can also be generic:

ProgramA generic box

Record Caja<T>
  Define contenido As T;
EndRecord
Subroutine abrir<T>(c As Caja<T>) As T
  Return c.contenido;
EndSubroutine
Algorithm Cajas
  Define numeros As Caja<Integer> <- Caja(7);
  Write abrir(numeros), " ", abrir(Caja("x"));
EndAlgorithm

Output

7 x

The program finishes normally.

Figure 3.12-1.A template with a type slot. Each use fills it with a concrete type and gets its own version.

At the top, the template Caja with a type slot T. Two arrows lead to two concrete versions, Caja of Integer and Caja of String.

3.12.2 What can be done with a value of type T

Inside the generic, T is opaque: the engine does not know what type it will be, so it only allows copying, passing, returning and storing the value. Adding it, comparing it or writing it is an error in the definition itself, even if every call used numbers.

ProgramComparing two values of type T

Subroutine mayor<T>(a As T, b As T) As T
  If a > b Then
    Return a;
  EndIf
  Return b;
EndSubroutine
Algorithm Mayor
  Write mayor(1, 2);
EndAlgorithm

Diagnostics

  • incompatibleOperandTypes · error · 2:6 · Incompatible types for operator >

The program finishes with an error.

In short

  • A type parameter <T> lets you write a single version for many types.
  • The concrete type is inferred in each call or written between < and >.
  • Inside the generic, T is only copied, passed, returned and stored.
  • Records, subroutines, classes, interfaces and variants can be generic.