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..*;

In reply to [perl 6] re reduction operators by blazar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.