On Tue, Dec 10, 2002 at 01:53:28PM +1100, Damian Conway wrote:
> And in those rare cases where you really do need partial caching, the
> simplest solution is to split the partially cached subroutine into a
> fully cached sub and an uncached sub:
> 
>   sub days_in_month(Str $month, Int $year)
>   {
>     $month = lc $month;
>     if $month eq 'feb'
>     {
>       my sub feb_days (Int $year) is cached {
>           my $leap = $year % 4 == 0
>           && ($year % 100 != 0 || $year % 400 == 0);
>           return $leap ? 29 : 28;
>       }
>       return feb_days($year);
>     }
> 
>     else
>     {
>       # Simple look-up, so caching would be counter-productive:
>       return %days{$month};  # %days was declared above (honest)
>     }
>   }

I don't think that works correctly.  This will create a new cached
sub each time $month eq 'feb'?  That'll generate a lot of cached
subs, values will be calculated each time $month eq 'feb, and none
of the values will ever be returned from any of those caches.

Schwern's approach of factoring out days_in_feb into a cached sub
is the same basic idea, and doesn't have this issue.

Z.

Reply via email to