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.

Perhaps there are only some edge cases which require calculation; or the
function is liable to be called with many invalid input values, which
can quickly be determined yield C<undef> and so which don't need
caching; or there is a pattern as to which sets of input parameters are
likely to be passed multiple times so the function only bother caching
those.

This would be more flexible than applying the caching to an entire sub.
The downside would be that somebody who wants to cache all their values
but has an algorithm that naturally leads to having many exit points
would have to remember to specify the caching on each of them -- that
may make this not worth bothering with.

Obviously C<cache_and_return> is a stupid placeholder name; were this to
be implemented a better syntax would be needed.  Slapping C<is cached>
on the end of the C<return> statement makes no sense, since it's not a
property of the thing being returned but of the input data to the
function.

Anybody else like this, or are we better off leaving things as they
were?

  [*0]  See the thread round about:

    http://groups.google.co.uk/groups?hl=en&threadm=3DCF8085.70902%40conway.org

Smylers

Reply via email to