I have a function that accepts a slurpy array and I want to constrain the contents of the array to Int between 0 and 255. So using raku's good documentation, I find I can write:
my &simp = -> *@a where { 0 <= $_.all <= 255 } { @a <<+>> 10 }
say &simp( 2, 3, 4);
# returns: [12 13 14]
As desired if I provide a list that is not in the range, then I get an error correctly, viz.
say &simp( 2,3,400 );
# Constraint type check failed in binding to parameter '@a'; expected anonymous constraint to be met but got Array ($[2, 3, 400])
Is it possible to name the constraint in some way, so that the error message can provide a better response?
If this were to be coded with multi subs, then a default sub with an error message would be provided. But for an inline pointy ??
You can try to generate the error in the where clause with the || operator.
my &simp = -> *@a where { (0 <= $_.all <= 255) || die 'not in Range' } { @a <<+>> 10 }
say &simp( 2, 3, 4);
# returns: [12 13 14]
say &simp( 2,3,400 );
#not in Range
What you want is a subset.
subset ByteSizedInt of Int where { 0 <= $_ <= 255 };
my &simp = -> ByteSizedInt *@a { @a <<+>> 10 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With