develooper Front page | perl.perl5.porters | Postings from January 2008

For 5.12: tail calls for methods

Thread Next
From:
Yuval Kogman
Date:
January 14, 2008 06:14
Subject:
For 5.12: tail calls for methods
Message ID:
20080114141430.GD10892@woobling.org
One thing that is very hard to do is make tail recursive OO code.

This is ugly with plain functions, but at least works:

	@_ = ( ... );
	goto $subref;

for OO this still works like this:

	my $subref = $object->can("method");

but 3 lines for a tail recursive method call is a price not worth
paying - i'd rather just waste memory for the sake of clarity.

I think the introduction of a statement modifier is in order, much
like 'Data::Alias' works (perhaps this is even feasable as a
module):

	tailcall $obj->method(@args);

	tailcall function(@args);

"tailcall" is an ugly keyword, maybe someone can think of something
new, but essentially it'll do the same as goto but also replacing
@_.

An alternative is to reuse the 'goto' keyword, as this is a syntax
error:

	perl -e 'sub foo { }; goto foo("bar")' 
	syntax error at -e line 1, near "goto foo("

This doesn't work for OO methods though, because they can already
return a label or a code reference:

	perl -e 'sub foo { }; my $o = bless {}; goto $o->foo("bar")'
	goto must have label at -e line 1.

So it's not quite obvious what is going on WRT the parsing here.

Anyway, this allows infinitely recursive code, which is a very nice
thing to have for stream processing, parsing, various loop
structures, etc. I frequently feel this is lacking in Perl.

-- 
  Yuval Kogman <nothingmuch@woobling.org>
http://nothingmuch.woobling.org  0xEBD27418


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About