Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name a constraint

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 ??

like image 573
Richard Hainsworth Avatar asked Dec 13 '19 13:12

Richard Hainsworth


2 Answers

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
like image 98
LuVa Avatar answered Nov 17 '22 07:11

LuVa


What you want is a subset.

subset ByteSizedInt of Int where { 0 <= $_ <= 255 };
my &simp = -> ByteSizedInt *@a { @a <<+>> 10 };
like image 20
Holli Avatar answered Nov 17 '22 06:11

Holli