Skip to content

SpecificationIII · Types and values

3.9

Variants

A variant is a type whose values can take several different shapes, each with its own data, like a figure that can be a circle or a rectangle.

Markdown version

3.9.1 How to write it

variant «Name»
  case «shape»(«field» As «type», …)
  case «shape»
endVariant

3.9.2 How it works

Each alternative is one possible shape of the value. An alternative may carry fields or none. A value is built with the variant's name, a dot and the alternative: Forma.Circulo(2).

To find out which shape a value has, Switch is used with patterns: each branch names an alternative and gives names to its fields, which only exist inside that branch.

ProgramThe area of each figure

Variant Forma
  Case Circulo(radio As Integer)
  Case Rectangulo(ancho As Integer, alto As Integer)
  Case Punto
EndVariant
Subroutine area(f As Forma) As Integer
  Define total As Integer <- 0;
  Switch f Do
    Forma.Circulo(r): total <- 3 * r * r;
    Forma.Rectangulo(a, h): total <- a * h;
    Forma.Punto: total <- 0;
  EndSwitch
  Return total;
EndSubroutine
Algorithm Areas
  Write area(Forma.Circulo(1));
  Write area(Forma.Rectangulo(3, 4));
  Write area(Forma.Punto);
EndAlgorithm

Output

3
12
0

The program finishes normally.

Figure 3.9-1.A variant is a box with several possible shapes. Switch looks at which shape it has and unpacks its fields.

A box with the type Forma and its three alternatives drawn: a circle, a rectangle and a point. Below, Switch f Do distributes the value into three branches, one per alternative.

Switch must cover all the alternatives or have Otherwise. That way, if a new alternative is added tomorrow, the engine points out every Switch that falls short.

ProgramA shape is forgotten

Variant Forma
  Case Circulo(radio As Integer)
  Case Punto
EndVariant
Algorithm Incompleto
  Define f As Forma <- Forma.Punto;
  Switch f Do
    Forma.Circulo(r): Write r;
  EndSwitch
EndAlgorithm

Diagnostics

  • nonExhaustiveSwitch · error · 7:3 · Missing branches: Punto

The program finishes with an error.

In short

  • A variant has several alternatives, each with its fields.
  • It is built with Variant.Alternative(…).
  • It is queried with Switch and patterns that unpack the fields.
  • Switch must cover every alternative.