Search code examples
raku

How do I find all possible values of an enum in Raku?


enum Direction <north east south west>;
for north, east, south, west -> $dir {
    say $dir;
    ...
}

I don't want to repeat the list of Direction values here. How can I programmatically get this list?

I haven't found anything in the documentation. Closest is .enums, but that returns a Map of (string) key to (integer) value, not enum values.


Solution

  • If the order doesn't matter

    enum Direction <north east south west>;
    Direction.pick(*).raku
    

    or

    enum Direction <north east south west>;
    Direction::.values.raku
    

    Sorted by value

    enum Direction «:2north :1east :south(10) :west(9)»;
    Direction.pick(*).sort.raku
    

    Sorted by definition; if you know first and last element

    enum Direction «:2north :1east :10south :9west»;
    (north, *.succ ... west).raku;
    

    if you don't

    enum Direction «:2north :1east :10south :9west»;
    (Direction.pick(*).first({ $_ === .pred }), *.succ ...^ * === *).raku