On Mon, Dec 09, 2002 at 08:36:20PM -0000, Smylers wrote:
> Last month's discussion on memoization[*0] had the consensus that
> C<cached> is the appropriate property name, used like so:
> 
>   sub square (Num $n) is cached { ... }
> 
> I was wondering whether it'd be better to have this specified per
> C<return> rather than per C<sub>.  That'd permit something a long the
> lines of:
> 
>   sub days_in_month(Str $month, Int $year)
>   {
>     $month = lc $month;
>     if $month eq 'feb'
>     {
>       # Do 'complicated' calculation and cache the result for later use:
>       my $leap = $year % 4 == 0
>           && ($year % 100 != 0 || $year % 400 == 0);
>       cache_and_return $leap ? 29 : 28;
>     }
> 
>     else
>     {
>       # Simple look-up, so caching would be counter-productive:
>       return %days{$month};  # %days was declared above (honest)
>     }
>   }
> 
> That way a function could decide to cache some return values but not all
> of them.

The example above is a classic example of premature optimization.  There's
nothing which ways the cache would be counter-productive for simple
calculations since the caching logic is nearly as simple.

However, if you *really* want to do partial caching and given that this is
an edge case, I'd say to just do it as two functions rather than making the
caching semantics more involved.

   my %days = (...);
   sub days_in_month(Str $month, Int $year)
   {
     $month = lc $month;
     return days_in_feb($year) if $month eq 'feb';
     return %days{$month};
   }

   sub days_in_feb(Int $year) is cached
   {
     # Do 'complicated' calculation and cache the result for later use:
     my $leap = $year % 4 == 0
         && ($year % 100 != 0 || $year % 400 == 0);
     return $leap ? 29 : 28;
   }

Of course there's nothing which says you can't just do *both*.
cache_and_return() is merely a function.  Write it, stick it in a library,
distribute for fun and/or profit.


-- 

Michael G. Schwern   <[EMAIL PROTECTED]>    http://www.pobox.com/~schwern/
Perl Quality Assurance      <[EMAIL PROTECTED]>         Kwalitee Is Job One
If God made anything more guerrila than your breast, I hope he kept it for
your father.

Reply via email to