Skip to content

Instantly share code, notes, and snippets.

@mcmillhj
Created April 26, 2018 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcmillhj/6447e9a051576cdd5adb61db0f848dba to your computer and use it in GitHub Desktop.
Save mcmillhj/6447e9a051576cdd5adb61db0f848dba to your computer and use it in GitHub Desktop.
Sharable Signatures?
#!perl6
my @alphabet = ('0' .. '9', 'A' .. 'Z', 'a' .. 'z').flat;
sub to-digits(Int $n is copy, Int $b where $b >= 2 && $b <= 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 $b >= 2 && $b <= 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 $b >= 2 && $b <= 62, Int $c where $c >= 2 && $c <= 62 --> Str) {
to-digits(from-digits($n, $b), $c);
}
say to-base('333', 10, 16);
say to-base('14D', 16, 10);
say to-base('333', 10, 62);
say to-base('14D', 16, 62);
@mcmillhj
Copy link
Author

I notice that I have the same signature constraint four times on the bases passed to this programs three functions. Is there a way to share that constraint?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment