Course of Raku / Advanced / More about built-in types / Enumerations 🆕 / Exercises / Traffic lights
Solution: Traffic lights
Here is a possible solution to the task.
Code
enum Light <red amber green>;
my Light $current = red;
say "$current is {$current.value}";
$current = amber;
say "$current is {$current.value}";
$current = green;
say "$current is {$current.value}";🦋 You can find the source code in the file traffic-enum.raku.
Output
red is 0
amber is 1
green is 2Comments
my Light $currentis an ordinary, mutable variable — only constrained to theLighttype. Assigning the next constant advances the light, and the number follows the name each time:0,1,2.$current++looks like it should step to the next light on its own, but it fails with a type-check error.++treats the constant as its plain number and hands back anInt(redbecomes1), and anIntno longer fits theLighttype. So you move the light by assigning the next constant, as above.The type constraint applies to every assignment, not just the first.
$currentwill takered,amber, orgreen, but assigning something that is not aLight— a bare number or a string — would be a type-check error.