Search code examples
enumsraku

How to get a seq of enum members filtering out some members


I have an enum list with actions and the members None and All. How do I create a sequence of enums that filters out None and All?

Test program in file filter-enum.raku:

#!/usr/bin/env raku
use v6.d;
enum A <All None one two three four>;
my SetHash of A $actions;

$actions .= new( A.enums.grep( *.key.match(/ All | None /).not) );
say $actions.raku;

output

$ raku -v
Welcome to Rakudo™ v2024.02-93-gc49e05d84.
Implementing the Raku® Programming Language v6.d.
Built on MoarVM version 2024.02.
$ raku filter-enum.raku
Type check failed in binding; expected A but got Pair (:one(2))
  in block <unit> at filter-enum.raku line 6

A workaround, or maybe a better approach, is to have two enums:

enum actions <one two three four>;
enum full-set (actions.keys, <None All>).flat;

Edit: This workaround doesn't work! So the answer below is best. But can a seq of enums be created by filtering?


Solution

  • You can use

    enum A <All None one two three four>;
    dd A::.values.grep: none(All, None); #or
    dd (All,*.succ...four).grep: none(All, None)
    

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