in reply to Callstack manipulation?

Motivation

I think I should better motivate this, to show that it's not an entirely esoterical approach...

With the following code I can easily simulate the semantics of List-Comprehensions which are quite popular in Python and Haskell.

{ my $list_ref=[]; sub gather (&){ my $code_ref=shift; my @list=(); my $safe=$list_ref; $list_ref=\@list; &$code_ref; $list_ref=$safe; return @list; } sub take { push @$list_ref, @_; return; } } @x= gather { for $c (1..10){ for $b (1..$c){ for $a (1..$b){ if ( $c**2 = += $b**2 + $a**2){ take [$c,$b,$a] } } } } }; }
(OK that's an extreme example for generating Pythagorean triples, but I hope the idea is clear and you don't blame me for the perl's need for curlies)

Now with the possibility to manipulate the call stack from within take(), it might be possible to use exactly the same syntax to produce a lazy iterator, just indicated by a switch. This could just be an additional attribute like @x=gather :lazy {...} to indicate a lazy generator.

An alterbnate approach would be to transform every opcode for calling "take()" into a "goto take()" followed by a reentry label. I tried this using B::Deparse and reevaluating the changed code into the symbol table, but that's not straightforwardly done, because of many special cases in perl's syntax, where you can't simply put the reentry-label just after the call...

That's why I beg for some peaces of the holy wisdom from the masters of opcodes ... ; )... before I start messing around by myself!

The potential of manipulating the call stack in this way would not only simplify this task, but Perl5 could get coroutines for free not talking about the cheaper "yield"-semantic in python and ruby.

Replies are listed 'Best First'.
Re^2: Callstack manipulation?
by Anonymous Monk on Nov 21, 2008 at 07:03 UTC
    I don't quite see what's missing in Coro that wouldn't help already - and coroutine switches are cheaper than a method call (on GNU/Linux).
      Saying that I'm mastering coro, would be a blatant lie!

      But for what I read in the pods, coro has it's own distinct variable space. So sharing variables and closures might be very complicated.

      And the docs from moritz for Perl6::GatherTake don't read as if he easily got along with coro.

      IMHO the solution I'm suggesting would be much simpler and lightweight. Why not a KISS approach?

      Cheers Rolf