Adam Turoff wrote:

 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'?
Nope. It simply declares C<feb_days> to be a *named* subroutine (i.e.
*not* a closure) that happens to be lexically scoped to inside
C<days_in_month>.

In other words, it works exactly as if I had left off the C<my>, except
(with the C<my>) it avoids polluting a global namespace with a subroutine
that's not relevant anywhere else.


That'll generate a lot of cached subs
Nope. It's a named subroutine. So "thar ken beeeee onla one!!!!" ;-)


values will be calculated each time $month eq 'feb, and none
of the values will ever be returned from any of those caches.
Nope.


Schwern's approach of factoring out days_in_feb into a cached sub
is the same basic idea, and doesn't have this issue.
That's true. But my version doesn't have the issue either, and also
elegantly illustrates why we're adding lexical subroutines to Perl 6. :-)

Damian


Reply via email to