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:
In the above program, the sum type Vehicle stands for the distinct types Car, Van and Bus.
The corresponding output is:
We can use the expression <var> is <Type> to determine if a variable currently holds an object of type <Type>:
This prints:
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:
Here is the program output:
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:
The output is as expected:
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!
Recent Comments