On 2019-12-04 00:40, ToddAndMargo via perl6-users wrote:
Hi All,

I am cooking up something where I want top pass a value to a sub, but I want to restrict what those values are.

For instance, things like

    AbortRetryIgnore
    CancelRetryContinue
    Help
    YesNo
    Maybe

And so on and so forth.

If the wrong value is passed, I want the checker to crash
the sub.

What is the best way of going about this?

Many thanks,
-T



Follow up:

This may be a duplicate. But I can't find it in my sent bin,
so I am re-sending my keeper on what I came up with that
I like.


Perl6: constraining variable in sub declarations:

References:

https://stackoverflow.com/questions/59222421/perl6-raku-how-to-i-restrict-the-values-allowed-in-a-variable
    https://docs.raku.org/type/Signature#index-entry-where_clause


Note: the `where clause` not confined to just subs.

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


Sample sub:

    sub abc( Str $x where * ~~ "abc" | "def" ) {say $x;}

    abc("abc")
    abc

    abc("def")
    def

    abc("hij")
    Constraint type check failed in binding to parameter '$x';
    expected anonymous constraint to be met but got Str ("hij")

Reply via email to