Share signature constraints across functions

时间:2018-04-26 17:03:16

标签: signature perl6

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?

1 个答案:

答案 0 :(得分:6)

事实证明没有,你不能在@moritz的回答中分享多个功能的签名:https://github.com/dankinder/httpmock

但是,你可以分享约束,方法是使用#{3}}作为#perl6 Freenode irc中概述的@zoffix:

subset Base of Int where 2 <= * <= 62;
sub to-digits(Int $n is copy, Base $b) {
  ...
}
...