Ethiopian multiplication: Difference between revisions
Content added Content deleted
(Updated D entry) |
(→{{header|Perl 6}}: modernize) |
||
Line 2,388: | Line 2,388: | ||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |
||
{{works with|Rakudo Star|2010-08}} |
|||
<lang perl6>sub halve (Int $n is rw) { $n div= 2 } |
<lang perl6>sub halve (Int $n is rw) { $n div= 2 } |
||
sub double (Int $n is rw) { $n *= 2 } |
sub double (Int $n is rw) { $n *= 2 } |
||
sub even (Int $n --> Bool) { $n %% 2 } |
sub even (Int $n --> Bool) { $n %% 2 } |
||
sub |
sub ethiopic-mult (Int $a is copy, Int $b is copy --> Int) { |
||
my Int $r = 0; |
my Int $r = 0; |
||
while $a { |
while $a { |
||
Line 2,402: | Line 2,400: | ||
} |
} |
||
return $r; |
return $r; |
||
} |
|||
}</lang> |
|||
say ethiopic-mult(17,34);</lang> |
|||
{{out}} |
|||
<pre>578</pre> |
|||
More succinctly using implicit typing, primed lambdas, and an infinite loop: |
More succinctly using implicit typing, primed lambdas, and an infinite loop: |
||
<lang perl6>sub |
<lang perl6>sub ethiopic-mult { |
||
my &halve = * div= 2; |
my &halve = * div= 2; |
||
my &double = * *= 2; |
my &double = * *= 2; |
||
Line 2,416: | Line 2,419: | ||
double $b; |
double $b; |
||
} |
} |
||
} |
|||
}</lang> |
|||
say ethiopic-mult(17,34);</lang> |
|||
More succinctly still, using a pure functional approach (reductions, mappings, lazy infinite sequences): |
More succinctly still, using a pure functional approach (reductions, mappings, lazy infinite sequences): |
||
<lang perl6>sub halve { $^n div 2 } |
<lang perl6>sub halve { $^n div 2 } |
||
Line 2,422: | Line 2,427: | ||
sub even { $^n %% 2 } |
sub even { $^n %% 2 } |
||
sub |
sub ethiopic-mult ($a, $b) { |
||
[+] |
[+] ($b, &double ... *) |
||
Z* |
|||
map { $^column_2 if !even $^column_1 }, |
|||
($a, &halve ... 0).map: { not even $^n } |
|||
} |
|||
}</lang> |
|||
say ethiopic-mult(17,34);</lang> |
|||
(same output) |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |