Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share signature constraints across functions

Tags:

signature

raku

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?

like image 347
Hunter McMillen Avatar asked Apr 26 '18 17:04

Hunter McMillen


1 Answers

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) {
  ...
}
...
like image 133
Hunter McMillen Avatar answered Dec 20 '22 05:12

Hunter McMillen