Skip to content

Instantly share code, notes, and snippets.

@mcmillhj mcmillhj/convert.p6
Created Apr 26, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

mcmillhj commented Apr 26, 2018

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
You can’t perform that action at this time.