Search code examples
constraintsrakunamed

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


Solution

  • 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