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

199 views Asked by At
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.

2

There are 2 answers

2
wamba On BEST ANSWER

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
6
raiph On

I'm not 100% sure what you mean, but one can reconstruct a symbol from its name:

enum Direction <north east south west>;

for Direction.enums {
    say .key, .key.WHAT, .value, .value.WHAT, ::(.key), ::(.key).WHAT;
}

displays:

east(Str)1(Int)east(Direction)
south(Str)2(Int)south(Direction)
west(Str)3(Int)west(Direction)
north(Str)0(Int)north(Direction)

The speculation doc for Enumerations says:

The enumeration typename itself may be used as a coercion operator from either the key name or a value.

But in my 2022 Rakudo it only works for values (integers in this case):

for Direction.enums {
    say Direction(.value), Direction(.value).WHAT;
}

displays:

east(Direction)
south(Direction)
west(Direction)
north(Direction)