Enum: Difference between revisions
From Coderwiki
More actions
new: info, example, other sum, other algebraic |
(No difference)
|
Latest revision as of 09:04, 15 August 2025
An enum is a sum type (a type of algebraic data type) in which its value represents one of a set number of possible states.
This makes invalid states unrepresentable, as the variable of the enum data type can only store certain values, nothing else.
Example
edit edit sourceSay you are writing a program to track animals in a zoo.
You could have an enum type called Animal to store the different animals in the zoo. Variables of this type could then only contain one of four 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.
Other sum types
edit edit sourceSee: Sum type
Other algebraic data types
edit edit sourceSee: Algebraic data type