Re: Coroutines in Perl 6 (Was: Re: Converting a Perl 5 "pseudo-continuation" to Perl 6)

2009-01-02 Thread Daniel Ruoso
Em Sex, 2009-01-02 às 08:34 -0300, Daniel Ruoso escreveu:
>   token routine_def: {...}

Actually, I was just looking at STD, and the correct token would be

  token routine_declarator:coro {   }

I was also looking at the spec files, and I realized that DRAFT S17
mentions coroutines, but its definition is a bit different then the one
I suggested, and the example poses a good reason:

  coro dbl { yield $_ * 2; yield $_; };
  (1..4).map:{ dbl($_) }
  # should result in 2 2 6 4

This example suggests that it will not install an alias in the caller
scope, but the code object itself stores its state.

The other difference is that falling out of a coro makes it restart
immediatly without returning any value (this one is a bit weird, I'd
expect it to return the last statement on the routine as well).

But one way or another yield (yes, I wrote it wrong in the previous
post) is still implemented as a control exception that is caught by the
implicit CONTROL block of the coro.

daniel



Coroutines in Perl 6 (Was: Re: Converting a Perl 5 "pseudo-continuation" to Perl 6)

2009-01-02 Thread Daniel Ruoso
Em Qui, 2009-01-01 às 12:34 -0800, Geoffrey Broadwell escreveu:
> In the below Perl 5 code, I refactored to pull the two halves of the PID
> file handling out of init_server(), but to do so, I had to return a sub
> from pid_file_handler() that acted as a "continuation".  The syntax is a
> bit ugly, though.  Is there a cleaner way to this in Perl 6?

Well,

If the STD Perl 6 doesn't support that, you can always declare a
sub-grammar that implements a 

  token routine_def: {...}

then you have something in the lines of:

  coro pid_file_handler {
  ... # first half
  yeld $something;
  ... # second half
  }

It's even easy to implement how it should work. Basically, yeld throws a
resumable control exception, the implicit "CONTROL" block of the routine
will then contain the code to handle that exception by aliasing the coro
in that state in the caller lexical scope, overriding the current
definition. And once the routine is called again, and returns or leaves,
you simply re-binds to the original routine. 

The above solution assumes a coro state is only available in the same
lexical scope as the first call, which may be a good idea to avoid
action-at-a-distance.

But maybe we even convince larry to push that into STD... since it's
such a nice feature...

daniel