perl6/raku: how to I restrict the values allowed in a variable?

You can simply add a where condition on the values

sub foo( Int $binary where * ~~ 0|1 ) { ... }

The where condition can be an arbitrary code block ( or even a sub I believe ).

If you need the condition multiple times you can create a subset.

subset BinaryInt of Int where * ~~ 0|1;

and subsequently use that in the signature

sub foo( BinaryInt $binary ) { ... }

Note, this isn't just limited to subroutine signatures. The constraints/conditions are enforced everywhere

my BinaryInt $i = 0; 
$i++; 
$i++;
# -> Type check failed in assignment to $i; expected BinaryInt but got Int (2)

You can also have subsets of subsets:

subset FalseBinaryInt of BinaryInt where not *;
my FalseBinaryInt $i = 0; 
$i++; 
# -> Type check failed in assignment to $i; expected FalseBinaryInt but got Int (1)

Edit: JJ down there is right. In this case an enumeration is useful. This

sub WinPopUp( Str $TitleStr, 
              Str $MessageStr,
              MessageBoxIcons $Icons where   * ~~ Exclamation |
                                                  Information |
              ...

Paired with an enumeration like

enum MessageBoxIcons is export {
    Exclamation => 0x00000030,
    Information => 0x00000040,
    ...
}

protects you from random typos, as enum members are symbols, and if you mispell one, the compiler will catch it. Also you don't have to look up the values to feed into MessageBoxW (which is what you are doing I assume).

Speaking of MessageBoxW, I would call your sub message-box (in Raku we tend to use CamelCase only for Classes and Types and stuff) just to stay consistent with MessageBoxW

Tags:

Raku