Numerical and alphabetical suffixes: Difference between revisions
Content deleted Content added
m corrected a misspelling. |
Thundergnat (talk | contribs) →{{header|Perl 6}}: Add a Perl 6 example |
||
Line 135: | Line 135: | ||
:* [[Longest common prefix]] |
:* [[Longest common prefix]] |
||
<br><br> |
<br><br> |
||
=={{header|Perl 6}}== |
|||
{{works with|Rakudo|2018.09}} |
|||
Scientific notation, while supported in Perl 6, is limited to IEE-752 64bit accuracy so there is some rounding on values using it. It would certainly be possible to implement a custom high accuracy conversion routine but I can't really see the point. |
|||
<lang perl6><PAIRs 2 SCOres 20 DOZens 12 GRoss 144 GREATGRoss 1728 |
|||
GOOGOLs 1e100> ~~ m:g/ ((<.:Lu>+) <.:Ll>*)\s+(\S+) /; |
|||
my %abr = |$/.map: { |
|||
my $abbrv = $_[0].Str.fc; |
|||
my $mag = +$_[1]; |
|||
|map { $abbrv.substr( 0, $_ ) => $mag }, |
|||
$_[0][0].Str.chars .. $abbrv.chars |
|||
} |
|||
my %suffix = flat %abr, |
|||
(<K M G T P E Z Y X W V U>».fc Z=> (1000, * * 1000 … *)), |
|||
(<Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui>».fc Z=> (1024, * * 1024 … *)); |
|||
my $reg = %suffix.keys.sort(-*.chars).join('|'); |
|||
sub comma ($i is copy) { |
|||
my $s = $i < 0 ?? '-' !! ''; |
|||
my $whole = $i.abs.floor; |
|||
my $frac = $i.abs - $whole ?? '.' ~ $i.abs.split('.')[1] !! ''; |
|||
$s ~ $whole.flip.comb(3).join(',').flip ~ $frac |
|||
} |
|||
sub units (Str $str) { |
|||
$str.fc ~~ /^(.+?)(<alpha>*)('!'*)$/; |
|||
my ($val, $unit, $fact) = +$0, $1.Str.fc, $2; |
|||
my @suf = $unit; |
|||
unless %suffix{$unit}:exists { |
|||
$unit ~~ /(<$reg>)+/; |
|||
@suf = $0; |
|||
} |
|||
my $ret = $val; |
|||
if @suf[0] { |
|||
$ret = [*] $val<>, |@suf.map: {%suffix{$_}} |
|||
} |
|||
if $fact.chars { |
|||
$ret = [*] ($val<>, * - $fact.chars …^ * < 2); |
|||
} |
|||
$ret |
|||
} |
|||
say sprintf "%16s: %s", $_, comma .&units for |
|||
<2greatGRo 24Gros 288Doz 1728pairs 172.8SCOre |
|||
1567 +1.567k 0.1567e-2m |
|||
25.123kK 25.123m 2.5123e-00002G |
|||
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei |
|||
-.25123e-34Vikki 2e-77gooGols |
|||
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!! |
|||
>;</lang> |
|||
{{out}} |
|||
<pre> 2greatGRo: 3,456 |
|||
24Gros: 3,456 |
|||
288Doz: 3,456 |
|||
1728pairs: 3,456 |
|||
172.8SCOre: 3,456 |
|||
1567: 1,567 |
|||
+1.567k: 1,567 |
|||
0.1567e-2m: 1,567 |
|||
25.123kK: 25,123,000 |
|||
25.123m: 25,123,000 |
|||
2.5123e-00002G: 25,123,000 |
|||
25.123kiKI: 26,343,374.848 |
|||
25.123Mi: 26,343,374.848 |
|||
2.5123e-00002Gi: 26,975,615.844352 |
|||
+.25123E-7Ei: 28,964,846,960.237816 |
|||
-.25123e-34Vikki: -33,394.19493810444 |
|||
2e-77gooGols: 199,999,999,999,999,983,222,784 |
|||
9!: 362,880 |
|||
9!!: 945 |
|||
9!!!: 162 |
|||
9!!!!: 45 |
|||
9!!!!!: 36 |
|||
9!!!!!!: 27 |
|||
9!!!!!!!: 18 |
|||
9!!!!!!!!: 9 |
|||
9!!!!!!!!!: 9</pre> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |