The Sum Type in V Programming Language

Written by on July 2, 2023 in Programming, Vlang with 0 Comments

A Sum data type in V language gives us a convenient way to hold objects of many distinct types (at any time, just one object) and hence is a discriminated union. For example, in C++ we have the variant type.

Here is an example of sum type in V language:

The "sum" Type

The “sum” Type

In the above program, the sum type Vehicle stands for the distinct types Car, Van and Bus.

The corresponding output is:

Program Output

Program Output

We can use the expression <var> is <Type> to determine if a variable currently holds an object of type <Type>:

Using "is a" Expression

Using “is a” Expression

This prints:

Output

Output

Likewise, we can use the expression <var> as <Type> to dynamically cast the current object held in <var> to the required <Type>. As expected, this will trigger a panic if the casting is performed on an invalid type.

This is shown below:

Dynamic Casting

Dynamic Casting

Here is the program output:

Result of Dynamic Casting

Result of Dynamic Casting

It is often convenient to use the match expression to work with the individual variant in a sum type. This is cleaner than using multiple if statements. The print_vehicle function that we wrote earlier can be rewritten thus:

Using "match" Expression

Using “match” Expression

The output is as expected:

Program Output

Program Output

The match statement must specify a pattern for all variants of the type, or must include the else branch to handle what has been left out.

Finally, the sum type is different from type inheritance as defined in object-oriented programming. In inheritance, when a class “D” is derived from a base class “B”, “D” is a “B”. In future, when another class “E” is derived from “D”, then that is also a “B”. In this sense, inheritance is a collection of one-way compatible open types. That is not the case with a sum type. It always defines a fixed and distinct set of types.

You can download the example source from here.

Have a wonderful weekend!

Tags: ,

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *

Top