Sum type: Difference between revisions
From Coderwiki
More actions
new: info, example, types |
(No difference)
|
Revision as of 08:55, 15 August 2025
A sum type is a type of algebraic data type. It is a user-defined data type that stores a fixed set of possible values. In other words, it is a choice of possibilities as to the data it contains.
Example
Suppose we are in a zoo and want to keep track of animals in the zoo.
An example of a sum type could be an Animal data type. Variables of this data type can only contain one of these 4 values:
- Parrot
- Monkey
- Tiger
- Giraffe
This has the benefit of making invalid state impossible: we are guaranteed that the value of an Animal variable will always be one of the 4 above.