in reply to Math fun.

Part 1:

use strict; use warnings; use List::Util qw( sum ); sub calcIt { our $r; local $r = sub { my ($depth) = @_; if ($depth == 0) { return sum 1..$_; } else { return sum map { $r->($depth-1) } 1..$_; } }; return $r->(5) for $_[0]; } print(calcIt(10), "\n"); # 11440 print(calcIt(20), "\n"); # 657800

Part 1, with memoization

use strict; use warnings; use List::Util qw( sum ); { my %memoize; sub calcIt { our $r; local $r = sub { my ($depth) = @_; return $memoize{"$depth:$_"} ||= ( ($depth ? sum map { $r->($depth-1) } 1..$_ : $_ * ( $_ + 1 ) / 2 ) ); }; return $r->(5) for $_[0]; } } print(calcIt(10), "\n"); # 11440 print(calcIt(20), "\n"); # 657800

Note: I changed 0.. to 1... You were adding way too many zeros.

Replies are listed 'Best First'.
Re^2: Math fun.
by BrowserUk (Patriarch) on Feb 13, 2007 at 19:25 UTC

      It's only compiled once, so it's not technically "thrown away". Only the reference to it is.

      I did it that way out of habit. Usually, the recursive bit would be a closure over args passed to the non-recursive bit. In this case, I didn't close over anything, so it doesn't need to be nested.