Luke Palmer wrote:
Jonadab the Unsightly One writes:
Rod Adams <[EMAIL PROTECTED]> writes:
One solution I see to this would be to have a "lazy return" of some kind, where you can send out what results you have so far, but not commit that your execution is over and still allow further results to be posted. For lack of better word coming to mind, I'll call a "lazy return" C<emit>.
Example above becomes:
sub MediansBy5 ([EMAIL PROTECTED]) {
while @list.length >= 5 {
emit (sort @list.splice(0,5))[2];
}}
That's actually a very good idea. That's why Perl 6 has it :-)
sub MediansBy5 ([EMAIL PROTECTED]) { gather { while @list >= 5 { # there's no .length; it's .elems take (sort @list.splice(0,5))[2]; } }
C<gather> returns a list of everything that was C<take>n inside of it. It does this by building a coroutine out of its argument, so it works lazily.
Luke
Better documentation on gather/take is merited.
Before starting this thread, I did a search on gather/take, thinking it might be what I needed, but all I could find was in A12 :
"We snuck in an example the new |gather|/|take| construct. It is still somewhat conjectural."
This was not very informative. Not to mention, it should be in S4/S9, not A12.
I would question the need for C<gather>, however. Could not a lone C<take>/C<emit> force the return value of the enclosing routine/closure to be a lazy list, and here's a few values to get things started?
To address Jonadab's questions:
1. What if anything do you propose is the evaluation value of emit?
The lazy list being constructed. Maybe a reference to it instead.
2. Should a subsequent implicit return behave differently than usual if some values have already been emitted?
This is a bit harder, but I would think it should emit it's parameters, then exit the routine.
The downside would be it forces list context where it might not have existed before, but it's the most consistent thought I have.
One other question: Would emit behave differently if the sub is called in a non-list context, such as void context or a scalar context?
My thought is that it returns a lazy list, and P6 rules for converting such a thing into a void or scalar would apply.
-- Rod Adams.