Occasionally I play with Project Euler's problems. Although they should be focused on smart algorithms, many of them can be easily solved with naive ones, often brute force, and unless there's a good reason not to do so, it's a pleasure for me to handle them with just a bunch of lines of Perl code.
Now, in a particular one I needed to adjoin the numbers 1,2,3,... (as strings) up to a length of at least 10^6. The code I used is:
my ($s,$x)=''; $s .= ++$x while length($s) < 1_000_000;
Here I'm bothered by the lexical $x: with a little more effort I may have hidden it suitably, but of course I was mostly concerned with completing the task quickly enough...
Coming to Perl 6, we have lazy lists evaluation there, and the reduce metaoperator (yes, I am aware of List::Util's reduce) and if I know in advance that the loop above stops at $x==185185 I can do, in a single statement:
my $s = [~] 1..185185;
And that is IMHO very elegant, and practical too. Yet, it would be nice if there were a way to have both the simplicity and elegance of that line of code and do the same as the Perl 5 code above without necessarily going the way of a literal translation.
Perhaps reduction operators could accept an adverb to specify a closure to which the accumulator they implicitly hold (well, those that do!) is passed so that it can be used in a test to end the cycle, as in:
my $s = [~] :while({.length<1_000_000}) 1..*;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: [perl 6] re reduction operators
by TimToady (Parson) on Aug 30, 2007 at 15:44 UTC | |
|
Re: [perl 6] re reduction operators
by ambrus (Abbot) on Aug 30, 2007 at 21:33 UTC | |
by blazar (Canon) on Sep 18, 2007 at 15:23 UTC |