【问题标题】:Share signature constraints across functions跨函数共享签名约束
【发布时间】:2018-04-26 17:03:16
【问题描述】:

给定一个简单的程序来转换基数:

#!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);
}

我发现我在整个程序中重复了我对提供的基础where * &gt;= 2 &amp;&amp; * &lt;= 62 的约束四次。查看Signatures 的文档,我发现您可以像这样保存签名:

my $sig = :(Int $a where $a >= 2 && $a <= 62);

有没有办法将此签名应用于多个函数和/或如何跨函数共享此约束?

【问题讨论】:

  • sub to-digits(Int:D $n, Int:D $b where 2..62 --&gt; Str:D) {[R~] @alphabet[$n.polymod: $b xx *]}
  • @BradGilbert 好的,这个解决方案真的很酷。比循环更优雅。
  • @BradGilbert :D 表示什么?
  • :D 是一种笑脸类型,表示已定义,参见en.wikipedia.org/wiki/Option_type#Perl_6

标签: signature raku


【解决方案1】:

事实证明,不,您不能在@moritz 在此答案中概述的多个函数之间共享签名:Can I use a standalone Signature as a signature in Perl 6?

但是,您可以通过使用Subset 来共享约束,如#perl6 Freenode irc 中所述的@zoffix:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 2018-02-28
    相关资源
    最近更新 更多