3 ms·
But you can do the same map square, then sum in ruby 1.9: puts (1..10).map{|x| x*x}.inject(:+) And if you don't like writing inject(:+) all the time, it's pre
by rauljara 15y ago
But you can do the same map square, then sum in ruby 1.9:
puts (1..10).map{|x| x*x}.inject(:+)
And if you don't like writing inject(:+) all the time, it's pretty easy to monkey patch in a sum method to either array or enumerable.
- draegtun 15y agoAnd Perl6 can also provide an expressive example: say [+] (1..10).map: {$_ * $_};
- JadeNB 15y agoNo need to wait for Perl 6: my $tot = 0; map { $tot += $_ } map { $_ ** 2 } 1 .. 10; say $tot; EDIT: Or, regarding List::Util (http://search.cpan.org/~gbarr/Scalar-List-Utils-1.23/lib/List/Util.pm http://search.cpan.org/~gbarr/Scalar-List-Utils-1.23/lib/Lis...) as part of Perl 5, say sum map { $_ ** 2 } 1 .. 10; EDIT 2: (Golfing is fun!) Or an Applescript-y sub the { @_ } sub of { @_ } sub squares { map { $_ ** 2 } @_ } say the sum of the squares of 1 .. 10;
- draegtun 15y agoNo need to wait for Perl 6 Absolutely :) use autobox::Core; # or perl5i::2 [1..10]->map(sub{ $_ ** 2 })->sum->say; Or if you like a double helping of sugar in your tea! use Whatever; [1..10]->map( &_ ** 2 )->sum->say;
- JadeNB 15y agoI thought `Whatever` was a joke, and had to go look it up on CPAN (http://search.cpan.org/~asg/Whatever-0.21/lib/Whatever.pm http://search.cpan.org/~asg/Whatever-0.21/lib/Whatever.pm). Not to belabour a joke, but the examples there suggest that the map should be map( $* ** 2 ) not map( &_ ** 2 )
- draegtun 15y agoNo it's quite a serious & well written module. Hopefully it will become part of perl5i - https://metacpan.org/module/perl5i https://metacpan.org/module/perl5i &_ is an explicit $_ You use $* or &* when you need to check $_[0] first. So &_ is more correct with general map but $* (and &*) will work also in this autobox example (in fact i had used it in my first edit but preferred aesthetics of &_ especially with previous usage of $* only being deprecated in 5.10). NB. Above in code just for aesthetics!