in reply to Re: (almost) foldl
in thread (almost) foldl
I came up with a similar, and arguably neater implementation:
sub sum{ ( shift()//return 0 ) + &sum } print sum( 1,2,3);; 6 print sum( 1 .. 100 );; Deep recursion on subroutine "main::sum" at 5050
but rejected it because 'sum' is a (glob) variable.
In theory, it is possible to avoid the naming of the sub, thereby achieving "anonymous recursion", by using the Y-combinator. And the Y-combinator has been achieved in Perl by a former regular here.
Putting it together you get:
print Y( sub{my$rec=shift; sub{(shift()//return 0) + &$rec }})->(1 .. +100);; 5050
But whilst that achieves the Y-combinators goal of recursion without adding the sub to the permanent namespace, it still requires the naming of the pesky closure $rec.
And of course, requires you to add the Y-combinator to the permanent namespace first:
sub Y { my ( $curried_rec ) = @_; sub { my ( $f1 ) = @_; $curried_rec->( sub { $f1->( $f1 )->( @_ ) } ) }->( sub { my ( $f2 ) = @_; $curried_rec->( sub { $f2->( $f2 )->( @_ ) } ) } ) }
And that's already more obfuscation as I want to wrap my brain around, even in an obfuscation section post!
My final thought is that the simplest mechanism that fits the OPs breif is just:
C:\test>perl -Mstrict -wE"say eval join'+',()" C:\test>perl -Mstrict -wE"say eval join'+',0" 0 C:\test>perl -Mstrict -wE"say eval join'+',-1" -1 C:\test>perl -Mstrict -wE"say eval join'+',-1..+3" 5
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: (almost) foldl
by Grimy (Pilgrim) on Jun 08, 2011 at 21:10 UTC | |
by BrowserUk (Patriarch) on Jun 08, 2011 at 21:17 UTC | |
by Grimy (Pilgrim) on Jun 08, 2011 at 21:28 UTC | |
by BrowserUk (Patriarch) on Jun 08, 2011 at 21:34 UTC | |
by Grimy (Pilgrim) on Jun 08, 2011 at 21:40 UTC | |
Re^3: (almost) foldl
by dk (Chaplain) on Jun 09, 2011 at 09:27 UTC | |
by BrowserUk (Patriarch) on Jun 09, 2011 at 10:23 UTC | |
by dk (Chaplain) on Jun 10, 2011 at 07:41 UTC | |
by TimToady (Parson) on Jun 10, 2011 at 23:29 UTC | |
by BrowserUk (Patriarch) on Jun 10, 2011 at 08:04 UTC |