develooper Front page | perl.perl5.porters | Postings from December 2010

Re: [perl #80628] [PATCH] __SUB__

Thread Previous | Thread Next
From:
Zefram
Date:
December 15, 2010 08:40
Subject:
Re: [perl #80628] [PATCH] __SUB__
Message ID:
20101215164020.GA15579@lake.fysh.org
demerphq wrote:
>The whole idea is to have a non-refcount incremented identifier that
>resolves to a reference to the currently executing subroutine.

This can actually be achieved without either a statically self-referential
function definition (requiring weak refs) or grubbing around in the
runtime stack.  Behold, the non-recursive definition of the recursive
implementation of factorial:

	my $w = sub { my($v, $x) = @_;
			sub { $x->(sub { $v->($v, $x)->(@_) }, @_) } };
	my $y = sub { $w->($w, $_[0]) };

	my $factorial =
		$y->(sub { $_[1] == 0 ? 1 : $_[1] * $_[0]->($_[1] - 1) });

	print $factorial->(5), "\n";

This technique can be extended to arbitrarily many mutually-recursive
functions, an area where __SUB__/${^SUB} falls down.

(Thanks to LeoNerd for inspiring me to go in a theoretical direction.)

-zefram

Thread Previous | 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