How to name a constraint
Asked Answered
H

2

7

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

Hoke answered 13/12, 2019 at 13:32 Comment(2)
The constraint wants to be where { 0 <= all($_) <= 255 } otherwise it's checking the length of the array. (And.... I dunno... I tried some stuff, nothing worked)Deference
@Scimon. Good call. New edited question. Originally, I didn't include the .all. No need for brackets as in your suggestion.Hoke
C
4

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
Coh answered 13/12, 2019 at 19:13 Comment(0)
A
3

What you want is a subset.

subset ByteSizedInt of Int where { 0 <= $_ <= 255 };
my &simp = -> ByteSizedInt *@a { @a <<+>> 10 };
Armistice answered 13/12, 2019 at 14:19 Comment(2)
Unfortunately a subset won't work on a slurpy array.Deference
Tried your code in REPL. Got: Slurpy positional parameters with type constraints are not supported.Hoke

© 2022 - 2024 — McMap. All rights reserved.