Reconsidering Exercise 1
Hao Wu provided a great comment showing how I could solve exercise one using sum
from List::Util
and grep
. I'd considered sum
but utilzed false laziness and didn't use it. I'd also considered grep, but did not immediately hit upon the elegant solution that Hao suggested and so went with a more verbose solution.
So, here are some new solutions.
Perl 5:
use v5.14;
use List::Util qw(sum);
my $max = (shift || 1000) - 1;
# For each number, collect it if it is a multiple of 3 or 5 (where % returns false)
my @multiples = grep { not $_ % 5 && $_ % 3 } 1 .. $max;
# and we're done.
say "My multiples are: @multiples";
say "Total: ", sum @multiples;
Short, elegant, more obviously correct. What's not to love?
Perl 5i:
use perl5i::2;
my $max = (shift || 1000) - 1;
# For each number, collect it if it is a multiple of 3 or 5 (where % returns false)
my @multiples = grep { not $_ % 5 && $_ % 3 } 1 .. $max;
# and we're done.
say "My multiiples are: @multiples";
say "Total: ", @multiples->sum;
Essentially idential. I could have used grep as a function on the list 1 .. $max
but it's more to ugly give grep
the subref it requires in that format.
Perl 6:
use v6;
sub MAIN( $max = 1000 ) {
# For each number, collect it if it is a multiple of 3 or 5 (where %% returns true)
my @multiples = grep { $_ %% 5 || $_ %% 3 }, 1 .. $max-1;
# and we're done.
"My multiples are: {@multiples}".say;
say "Total: ", [+] @multiples;
}
I thought that maybe a gather/take would be better than the grep here, but I'm pretty sure that's mistaken. I do like %%
, that's pretty neat. "{@array}"
threw me for a bit, but I did like [+]
for reduce.
And approximate time comparison:
jarich@blackberry:~/polyglot$ time perl m2.pl 30
My multiples are: 3 5 6 9 10 12 15 18 20 21 24 25 27
Total: 195
real 0m0.050s
user 0m0.032s
sys 0m0.016s
jarich@blackberry:~/polyglot$ time perl5i m2.p5i 30
My multiples are: 3 5 6 9 10 12 15 18 20 21 24 25 27
Total: 195
real 0m0.671s
user 0m0.624s
sys 0m0.040s
jarich@blackberry:~/polyglot$ time perl6 m2.p6 30
My multiples are: 3 5 6 9 10 12 15 18 20 21 24 25 27
Total: 195
real 0m8.731s
user 0m8.561s
sys 0m0.116s