Tagged unions

Tagged unions can hold a value from a fixed selection of types.

union Shape
{
    Dot,
    Square(Int),
    Rectangle(Int, Int),
}

val dot        = Shape::Dot
val square1    = Shape::Square(10)
val rectangle1 = Shape::Rectangle(5, 15)thp
    
Syntax error: Unexpected token `Shape`, expected a new line at line 1:6

Pattern matching

match shape_1
case ::Square(side)
{
    print("Area of the square: {side * side}")
}
case ::Rectangle(length, height)
{
    print("Area of the rectangle: {length * height}")
}thp
    
Syntax error: Expected an statement or an expresion at the top level. at line 1:0

Internal representation

When compiled down to PHP, tagged unions are a combination of an enum and an array.

THP creates an enum of the same name and with the same cases, and the values are contained as part of an array.

// The first snippet is compiled to:
enum Shape
{
    case Dot;
    case Square;
    case Rectangle;
}

$dot        = [Shape::Dot];
$square1    = [Shape::Square, 10];
$rectangle1 = [Shape::Rectangle, 5, 15]