Given a simple program to convert to/from bases:
#!perl6
my @alphabet = ('0' .. '9', 'A' .. 'Z', 'a' .. 'z').flat;
sub to-digits(Int $n is copy, Int $b where 2 <= * <= 62 --> Str) {
my @digits;
while $n > 0 {
@digits.push(@alphabet[$n % $b]);
$n = $n div $b;
}
@digits.reverse.join;
}
sub from-digits(Str $digits, Int $b where 2 <= * <= 62 --> Int) {
my $n = 0;
for $digits.comb -> $d {
$n = $b * $n + @alphabet.first({ $_ eq $d }, :k);
}
$n;
}
sub to-base(
Str $n,
Int $b where 2 <= * <= 62,
Int $c where 2 <= * <= 62 --> Str) {
to-digits(from-digits($n, $b), $c);
}
I find that I repeat my constraint on the supplied base, where * >= 2 && * <= 62
, four times throughout my program. Looking at the documentation for Signatures
I see that you can save out a signature like so:
my $sig = :(Int $a where $a >= 2 && $a <= 62);
Is there a way that this Signature can be applied to multiple functions and/or how can I share this constraint across functions?
It turns out that no, you cannot share signatures across multiple functions as outlined by @moritz in this answer: Can I use a standalone Signature as a signature in Perl 6?
However, you can share constraints by using a Subset
as @zoffix outlined in the #perl6 Freenode irc:
subset Base of Int where 2 <= * <= 62;
sub to-digits(Int $n is copy, Base $b) {
...
}
...
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