Ethiopian multiplication: Difference between revisions
Rename Perl 6 -> Raku, alphabetize, minor clean-up
(Add Jsish) |
Thundergnat (talk | contribs) (Rename Perl 6 -> Raku, alphabetize, minor clean-up) |
||
Line 2,549:
}
</lang>
=={{header|Locomotive Basic}}==
Line 3,255 ⟶ 3,256:
disp(ethiopicmult(17, 34, true))</lang>
=={{header|Oforth}}==
Line 3,411:
print ethiopicmult(17,34, 1), "\n";</lang>
=={{header|Perl 6}}==▼
<lang perl6>sub halve (Int $n is rw) { $n div= 2 }▼
sub double (Int $n is rw) { $n *= 2 }▼
sub even (Int $n --> Bool) { $n %% 2 }▼
sub ethiopic-mult (Int $a is copy, Int $b is copy --> Int) {▼
my Int $r = 0;▼
while $a {▼
even $a or $r += $b;▼
halve $a;▼
double $b;▼
}▼
return $r;▼
}▼
say ethiopic-mult(17,34);</lang>▼
{{out}}▼
578▼
More succinctly using implicit typing, primed lambdas, and an infinite loop:▼
<lang perl6>sub ethiopic-mult {▼
my &halve = * div= 2;▼
my &double = * *= 2;▼
my &even = * %% 2;▼
my ($a,$b) = @_;▼
my $r;▼
loop {▼
even $a or $r += $b;▼
halve $a or return $r;▼
double $b;▼
}▼
}▼
say ethiopic-mult(17,34);</lang>▼
More succinctly still, using a pure functional approach (reductions, mappings, lazy infinite sequences):▼
<lang perl6>sub halve { $^n div 2 }▼
sub double { $^n * 2 }▼
sub even { $^n %% 2 }▼
sub ethiopic-mult ($a, $b) {▼
[+] ($b, &double ... *)▼
Z*▼
($a, &halve ... 0).map: { not even $^n }▼
}▼
say ethiopic-mult(17,34);</lang>(same output)▼
=={{header|Phix}}==
Line 4,234 ⟶ 4,187:
(ethiopian-multiply 17 34) ; -> 578</lang>
(formerly Perl 6)
▲<lang perl6>sub halve (Int $n is rw) { $n div= 2 }
▲sub double (Int $n is rw) { $n *= 2 }
▲sub even (Int $n --> Bool) { $n %% 2 }
▲sub ethiopic-mult (Int $a is copy, Int $b is copy --> Int) {
▲ my Int $r = 0;
▲ while $a {
▲ even $a or $r += $b;
▲ halve $a;
▲ double $b;
▲ }
▲ return $r;
▲}
▲say ethiopic-mult(17,34);</lang>
▲{{out}}
▲ 578
▲More succinctly using implicit typing, primed lambdas, and an infinite loop:
▲<lang perl6>sub ethiopic-mult {
▲ my &halve = * div= 2;
▲ my &double = * *= 2;
▲ my &even = * %% 2;
▲ my ($a,$b) = @_;
▲ my $r;
▲ loop {
▲ even $a or $r += $b;
▲ halve $a or return $r;
▲ double $b;
▲ }
▲}
▲say ethiopic-mult(17,34);</lang>
▲More succinctly still, using a pure functional approach (reductions, mappings, lazy infinite sequences):
▲<lang perl6>sub halve { $^n div 2 }
▲sub double { $^n * 2 }
▲sub even { $^n %% 2 }
▲sub ethiopic-mult ($a, $b) {
▲ [+] ($b, &double ... *)
▲ Z*
▲ ($a, &halve ... 0).map: { not even $^n }
▲}
▲say ethiopic-mult(17,34);</lang>(same output)
=={{header|Rascal}}==
|