Plan 9 from Bell Labs’s /usr/web/sources/contrib/gabidiaz/root/sys/man/2perl/Memoize

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  | will give a
.\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
.\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
.    de IX
.    tm Index:\\$1\t\\n%\t"\\$2"
..
.    nr % 0
.    rr F
.\}
.\"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "Memoize 3"
.TH Memoize 3 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
Memoize \- Make functions faster by trading space for time
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
.Vb 4
\&        # This is the documentation for Memoize 1.01
\&        use Memoize;
\&        memoize('slow_function');
\&        slow_function(arguments);    # Is faster than it was before
.Ve
.PP
This is normally all you need to know.  However, many options are available:
.PP
.Vb 1
\&        memoize(function, options...);
.Ve
.PP
Options include:
.PP
.Vb 2
\&        NORMALIZER => function
\&        INSTALL => new_name
.Ve
.PP
.Vb 4
\&        SCALAR_CACHE => 'MEMORY'
\&        SCALAR_CACHE => ['HASH', \e%cache_hash ]
\&        SCALAR_CACHE => 'FAULT'
\&        SCALAR_CACHE => 'MERGE'
.Ve
.PP
.Vb 4
\&        LIST_CACHE => 'MEMORY'
\&        LIST_CACHE => ['HASH', \e%cache_hash ]
\&        LIST_CACHE => 'FAULT'
\&        LIST_CACHE => 'MERGE'
.Ve
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
`Memoizing' a function makes it faster by trading space for time.  It
does this by caching the return values of the function in a table.
If you call the function again with the same arguments, \f(CW\*(C`memoize\*(C'\fR
jumps in and gives you the value out of the table, instead of letting
the function compute the value all over again.
.PP
Here is an extreme example.  Consider the Fibonacci sequence, defined
by the following function:
.PP
.Vb 6
\&        # Compute Fibonacci numbers
\&        sub fib {
\&          my $n = shift;
\&          return $n if $n < 2;
\&          fib($n-1) + fib($n-2);
\&        }
.Ve
.PP
This function is very slow.  Why?  To compute fib(14), it first wants
to compute fib(13) and fib(12), and add the results.  But to compute
fib(13), it first has to compute fib(12) and fib(11), and then it
comes back and computes fib(12) all over again even though the answer
is the same.  And both of the times that it wants to compute fib(12),
it has to compute fib(11) from scratch, and then it has to do it
again each time it wants to compute fib(13).  This function does so
much recomputing of old results that it takes a really long time to
run\-\-\-fib(14) makes 1,200 extra recursive calls to itself, to compute
and recompute things that it already computed.
.PP
This function is a good candidate for memoization.  If you memoize the
`fib' function above, it will compute fib(14) exactly once, the first
time it needs to, and then save the result in a table.  Then if you
ask for fib(14) again, it gives you the result out of the table.
While computing fib(14), instead of computing fib(12) twice, it does
it once; the second time it needs the value it gets it from the table.
It doesn't compute fib(11) four times; it computes it once, getting it
from the table the next three times.  Instead of making 1,200
recursive calls to `fib', it makes 15.  This makes the function about
150 times faster.
.PP
You could do the memoization yourself, by rewriting the function, like
this:
.PP
.Vb 9
\&        # Compute Fibonacci numbers, memoized version
\&        { my @fib;
\&          sub fib {
\&            my $n = shift;
\&            return $fib[$n] if defined $fib[$n];
\&            return $fib[$n] = $n if $n < 2;
\&            $fib[$n] = fib($n-1) + fib($n-2);
\&          }
\&        }
.Ve
.PP
Or you could use this module, like this:
.PP
.Vb 2
\&        use Memoize;
\&        memoize('fib');
.Ve
.PP
.Vb 1
\&        # Rest of the fib function just like the original version.
.Ve
.PP
This makes it easy to turn memoizing on and off.
.PP
Here's an even simpler example: I wrote a simple ray tracer; the
program would look in a certain direction, figure out what it was
looking at, and then convert the `color' value (typically a string
like `red') of that object to a red, green, and blue pixel value, like
this:
.PP
.Vb 6
\&    for ($direction = 0; $direction < 300; $direction++) {
\&      # Figure out which object is in direction $direction
\&      $color = $object->{color};
\&      ($r, $g, $b) = @{&ColorToRGB($color)};
\&      ...
\&    }
.Ve
.PP
Since there are relatively few objects in a picture, there are only a
few colors, which get looked up over and over again.  Memoizing
\&\f(CW\*(C`ColorToRGB\*(C'\fR sped up the program by several percent.
.SH "DETAILS"
.IX Header "DETAILS"
This module exports exactly one function, \f(CW\*(C`memoize\*(C'\fR.  The rest of the
functions in this package are None of Your Business.
.PP
You should say
.PP
.Vb 1
\&        memoize(function)
.Ve
.PP
where \f(CW\*(C`function\*(C'\fR is the name of the function you want to memoize, or
a reference to it.  \f(CW\*(C`memoize\*(C'\fR returns a reference to the new,
memoized version of the function, or \f(CW\*(C`undef\*(C'\fR on a non-fatal error.
At present, there are no non-fatal errors, but there might be some in
the future.
.PP
If \f(CW\*(C`function\*(C'\fR was the name of a function, then \f(CW\*(C`memoize\*(C'\fR hides the
old version and installs the new memoized version under the old name,
so that \f(CW\*(C`&function(...)\*(C'\fR actually invokes the memoized version.
.SH "OPTIONS"
.IX Header "OPTIONS"
There are some optional options you can pass to \f(CW\*(C`memoize\*(C'\fR to change
the way it behaves a little.  To supply options, invoke \f(CW\*(C`memoize\*(C'\fR
like this:
.PP
.Vb 5
\&        memoize(function, NORMALIZER => function,
\&                          INSTALL => newname,
\&                          SCALAR_CACHE => option,
\&                          LIST_CACHE => option
\&                         );
.Ve
.PP
Each of these options is optional; you can include some, all, or none
of them.
.Sh "\s-1INSTALL\s0"
.IX Subsection "INSTALL"
If you supply a function name with \f(CW\*(C`INSTALL\*(C'\fR, memoize will install
the new, memoized version of the function under the name you give.
For example, 
.PP
.Vb 1
\&        memoize('fib', INSTALL => 'fastfib')
.Ve
.PP
installs the memoized version of \f(CW\*(C`fib\*(C'\fR as \f(CW\*(C`fastfib\*(C'\fR; without the
\&\f(CW\*(C`INSTALL\*(C'\fR option it would have replaced the old \f(CW\*(C`fib\*(C'\fR with the
memoized version.  
.PP
To prevent \f(CW\*(C`memoize\*(C'\fR from installing the memoized version anywhere, use
\&\f(CW\*(C`INSTALL => undef\*(C'\fR.
.Sh "\s-1NORMALIZER\s0"
.IX Subsection "NORMALIZER"
Suppose your function looks like this:
.PP
.Vb 6
\&        # Typical call: f('aha!', A => 11, B => 12);
\&        sub f {
\&          my $a = shift;
\&          my %hash = @_;
\&          $hash{B} ||= 2;  # B defaults to 2
\&          $hash{C} ||= 7;  # C defaults to 7
.Ve
.PP
.Vb 2
\&          # Do something with $a, %hash
\&        }
.Ve
.PP
Now, the following calls to your function are all completely equivalent:
.PP
.Vb 6
\&        f(OUCH);
\&        f(OUCH, B => 2);
\&        f(OUCH, C => 7);
\&        f(OUCH, B => 2, C => 7);
\&        f(OUCH, C => 7, B => 2);
\&        (etc.)
.Ve
.PP
However, unless you tell \f(CW\*(C`Memoize\*(C'\fR that these calls are equivalent,
it will not know that, and it will compute the values for these
invocations of your function separately, and store them separately.
.PP
To prevent this, supply a \f(CW\*(C`NORMALIZER\*(C'\fR function that turns the
program arguments into a string in a way that equivalent arguments
turn into the same string.  A \f(CW\*(C`NORMALIZER\*(C'\fR function for \f(CW\*(C`f\*(C'\fR above
might look like this:
.PP
.Vb 5
\&        sub normalize_f {
\&          my $a = shift;
\&          my %hash = @_;
\&          $hash{B} ||= 2;
\&          $hash{C} ||= 7;
.Ve
.PP
.Vb 2
\&          join(',', $a, map ($_ => $hash{$_}) sort keys %hash);
\&        }
.Ve
.PP
Each of the argument lists above comes out of the \f(CW\*(C`normalize_f\*(C'\fR
function looking exactly the same, like this:
.PP
.Vb 1
\&        OUCH,B,2,C,7
.Ve
.PP
You would tell \f(CW\*(C`Memoize\*(C'\fR to use this normalizer this way:
.PP
.Vb 1
\&        memoize('f', NORMALIZER => 'normalize_f');
.Ve
.PP
\&\f(CW\*(C`memoize\*(C'\fR knows that if the normalized version of the arguments is
the same for two argument lists, then it can safely look up the value
that it computed for one argument list and return it as the result of
calling the function with the other argument list, even if the
argument lists look different.
.PP
The default normalizer just concatenates the arguments with character
28 in between.  (In \s-1ASCII\s0, this is called \s-1FS\s0 or control\-\e.)  This
always works correctly for functions with only one string argument,
and also when the arguments never contain character 28.  However, it
can confuse certain argument lists:
.PP
.Vb 3
\&        normalizer("a\e034", "b")
\&        normalizer("a", "\e034b")
\&        normalizer("a\e034\e034b")
.Ve
.PP
for example.
.PP
Since hash keys are strings, the default normalizer will not
distinguish between \f(CW\*(C`undef\*(C'\fR and the empty string.  It also won't work
when the function's arguments are references.  For example, consider a
function \f(CW\*(C`g\*(C'\fR which gets two arguments: A number, and a reference to
an array of numbers:
.PP
.Vb 1
\&        g(13, [1,2,3,4,5,6,7]);
.Ve
.PP
The default normalizer will turn this into something like
\&\f(CW"13\e034ARRAY(0x436c1f)"\fR.  That would be all right, except that a
subsequent array of numbers might be stored at a different location
even though it contains the same data.  If this happens, \f(CW\*(C`Memoize\*(C'\fR
will think that the arguments are different, even though they are
equivalent.  In this case, a normalizer like this is appropriate:
.PP
.Vb 1
\&        sub normalize { join ' ', $_[0], @{$_[1]} }
.Ve
.PP
For the example above, this produces the key \*(L"13 1 2 3 4 5 6 7\*(R".
.PP
Another use for normalizers is when the function depends on data other
than those in its arguments.  Suppose you have a function which
returns a value which depends on the current hour of the day:
.PP
.Vb 10
\&        sub on_duty {
\&          my ($problem_type) = @_;
\&          my $hour = (localtime)[2];
\&          open my $fh, "$DIR/$problem_type" or die...;
\&          my $line;
\&          while ($hour-- > 0)
\&            $line = <$fh>;
\&          } 
\&          return $line;
\&        }
.Ve
.PP
At 10:23, this function generates the 10th line of a data file; at
3:45 \s-1PM\s0 it generates the 15th line instead.  By default, \f(CW\*(C`Memoize\*(C'\fR
will only see the \f(CW$problem_type\fR argument.  To fix this, include the
current hour in the normalizer:
.PP
.Vb 1
\&        sub normalize { join ' ', (localtime)[2], @_ }
.Ve
.PP
The calling context of the function (scalar or list context) is
propagated to the normalizer.  This means that if the memoized
function will treat its arguments differently in list context than it
would in scalar context, you can have the normalizer function select
its behavior based on the results of \f(CW\*(C`wantarray\*(C'\fR.  Even if called in
a list context, a normalizer should still return a single string.
.ie n .Sh """SCALAR_CACHE""\fP, \f(CW""LIST_CACHE"""
.el .Sh "\f(CWSCALAR_CACHE\fP, \f(CWLIST_CACHE\fP"
.IX Subsection "SCALAR_CACHE, LIST_CACHE"
Normally, \f(CW\*(C`Memoize\*(C'\fR caches your function's return values into an
ordinary Perl hash variable.  However, you might like to have the
values cached on the disk, so that they persist from one run of your
program to the next, or you might like to associate some other
interesting semantics with the cached values.
.PP
There's a slight complication under the hood of \f(CW\*(C`Memoize\*(C'\fR: There are
actually \fItwo\fR caches, one for scalar values and one for list values.
When your function is called in scalar context, its return value is
cached in one hash, and when your function is called in list context,
its value is cached in the other hash.  You can control the caching
behavior of both contexts independently with these options.
.PP
The argument to \f(CW\*(C`LIST_CACHE\*(C'\fR or \f(CW\*(C`SCALAR_CACHE\*(C'\fR must either be one of
the following four strings:
.PP
.Vb 4
\&        MEMORY
\&        FAULT
\&        MERGE
\&        HASH
.Ve
.PP
or else it must be a reference to a list whose first element is one of
these four strings, such as \f(CW\*(C`[HASH, arguments...]\*(C'\fR.
.ie n .IP """MEMORY""" 4
.el .IP "\f(CWMEMORY\fR" 4
.IX Item "MEMORY"
\&\f(CW\*(C`MEMORY\*(C'\fR means that return values from the function will be cached in
an ordinary Perl hash variable.  The hash variable will not persist
after the program exits.  This is the default.
.ie n .IP """HASH""" 4
.el .IP "\f(CWHASH\fR" 4
.IX Item "HASH"
\&\f(CW\*(C`HASH\*(C'\fR allows you to specify that a particular hash that you supply
will be used as the cache.  You can tie this hash beforehand to give
it any behavior you want.
.Sp
A tied hash can have any semantics at all.  It is typically tied to an
on-disk database, so that cached values are stored in the database and
retrieved from it again when needed, and the disk file typically
persists after your program has exited.  See \f(CW\*(C`perltie\*(C'\fR for more
complete details about \f(CW\*(C`tie\*(C'\fR.
.Sp
A typical example is:
.Sp
.Vb 3
\&        use DB_File;
\&        tie my %cache => 'DB_File', $filename, O_RDWR|O_CREAT, 0666;
\&        memoize 'function', SCALAR_CACHE => [HASH => \e%cache];
.Ve
.Sp
This has the effect of storing the cache in a \f(CW\*(C`DB_File\*(C'\fR database
whose name is in \f(CW$filename\fR.  The cache will persist after the
program has exited.  Next time the program runs, it will find the
cache already populated from the previous run of the program.  Or you
can forcibly populate the cache by constructing a batch program that
runs in the background and populates the cache file.  Then when you
come to run your real program the memoized function will be fast
because all its results have been precomputed.
.ie n .IP """TIE""" 4
.el .IP "\f(CWTIE\fR" 4
.IX Item "TIE"
This option is no longer supported.  It is still documented only to
aid in the debugging of old programs that use it.  Old programs should
be converted to use the \f(CW\*(C`HASH\*(C'\fR option instead.
.Sp
.Vb 1
\&        memoize ... [TIE, PACKAGE, ARGS...]
.Ve
.Sp
is merely a shortcut for
.Sp
.Vb 5
\&        require PACKAGE;
\&        { my %cache;
\&          tie %cache, PACKAGE, ARGS...;
\&        }
\&        memoize ... [HASH => \e%cache];
.Ve
.ie n .IP """FAULT""" 4
.el .IP "\f(CWFAULT\fR" 4
.IX Item "FAULT"
\&\f(CW\*(C`FAULT\*(C'\fR means that you never expect to call the function in scalar
(or list) context, and that if \f(CW\*(C`Memoize\*(C'\fR detects such a call, it
should abort the program.  The error message is one of
.Sp
.Vb 2
\&        `foo' function called in forbidden list context at line ...
\&        `foo' function called in forbidden scalar context at line ...
.Ve
.ie n .IP """MERGE""" 4
.el .IP "\f(CWMERGE\fR" 4
.IX Item "MERGE"
\&\f(CW\*(C`MERGE\*(C'\fR normally means the function does not distinguish between list
and sclar context, and that return values in both contexts should be
stored together.  \f(CW\*(C`LIST_CACHE => MERGE\*(C'\fR means that list context
return values should be stored in the same hash that is used for
scalar context returns, and \f(CW\*(C`SCALAR_CACHE => MERGE\*(C'\fR means the
same, mutatis mutandis.  It is an error to specify \f(CW\*(C`MERGE\*(C'\fR for both,
but it probably does something useful.
.Sp
Consider this function:
.Sp
.Vb 1
\&        sub pi { 3; }
.Ve
.Sp
Normally, the following code will result in two calls to \f(CW\*(C`pi\*(C'\fR:
.Sp
.Vb 3
\&    $x = pi();
\&    ($y) = pi();
\&    $z = pi();
.Ve
.Sp
The first call caches the value \f(CW3\fR in the scalar cache; the second
caches the list \f(CW\*(C`(3)\*(C'\fR in the list cache.  The third call doesn't call
the real \f(CW\*(C`pi\*(C'\fR function; it gets the value from the scalar cache.
.Sp
Obviously, the second call to \f(CW\*(C`pi\*(C'\fR is a waste of time, and storing
its return value is a waste of space.  Specifying \f(CW\*(C`LIST_CACHE =>
MERGE\*(C'\fR will make \f(CW\*(C`memoize\*(C'\fR use the same cache for scalar and list
context return values, so that the second call uses the scalar cache
that was populated by the first call.  \f(CW\*(C`pi\*(C'\fR ends up being called only
once, and both subsequent calls return \f(CW3\fR from the cache, regardless
of the calling context.
.Sp
Another use for \f(CW\*(C`MERGE\*(C'\fR is when you want both kinds of return values
stored in the same disk file; this saves you from having to deal with
two disk files instead of one.  You can use a normalizer function to
keep the two sets of return values separate.  For example:
.Sp
.Vb 1
\&        tie my %cache => 'MLDBM', 'DB_File', $filename, ...;
.Ve
.Sp
.Vb 5
\&        memoize 'myfunc',
\&          NORMALIZER => 'n',
\&          SCALAR_CACHE => [HASH => \e%cache],
\&          LIST_CACHE => MERGE,
\&        ;
.Ve
.Sp
.Vb 5
\&        sub n {
\&          my $context = wantarray() ? 'L' : 'S';
\&          # ... now compute the hash key from the arguments ...
\&          $hashkey = "$context:$hashkey";
\&        }
.Ve
.Sp
This normalizer function will store scalar context return values in
the disk file under keys that begin with \f(CW\*(C`S:\*(C'\fR, and list context
return values under keys that begin with \f(CW\*(C`L:\*(C'\fR.
.SH "OTHER FACILITIES"
.IX Header "OTHER FACILITIES"
.ie n .Sh """unmemoize"""
.el .Sh "\f(CWunmemoize\fP"
.IX Subsection "unmemoize"
There's an \f(CW\*(C`unmemoize\*(C'\fR function that you can import if you want to.
Why would you want to?  Here's an example: Suppose you have your cache
tied to a \s-1DBM\s0 file, and you want to make sure that the cache is
written out to disk if someone interrupts the program.  If the program
exits normally, this will happen anyway, but if someone types
control-C or something then the program will terminate immediately
without synchronizing the database.  So what you can do instead is
.PP
.Vb 1
\&    $SIG{INT} = sub { unmemoize 'function' };
.Ve
.PP
\&\f(CW\*(C`unmemoize\*(C'\fR accepts a reference to, or the name of a previously
memoized function, and undoes whatever it did to provide the memoized
version in the first place, including making the name refer to the
unmemoized version if appropriate.  It returns a reference to the
unmemoized version of the function.
.PP
If you ask it to unmemoize a function that was never memoized, it
croaks.
.ie n .Sh """flush_cache"""
.el .Sh "\f(CWflush_cache\fP"
.IX Subsection "flush_cache"
\&\f(CW\*(C`flush_cache(function)\*(C'\fR will flush out the caches, discarding \fIall\fR
the cached data.  The argument may be a function name or a reference
to a function.  For finer control over when data is discarded or
expired, see the documentation for \f(CW\*(C`Memoize::Expire\*(C'\fR, included in
this package.
.PP
Note that if the cache is a tied hash, \f(CW\*(C`flush_cache\*(C'\fR will attempt to
invoke the \f(CW\*(C`CLEAR\*(C'\fR method on the hash.  If there is no \f(CW\*(C`CLEAR\*(C'\fR
method, this will cause a run-time error.
.PP
An alternative approach to cache flushing is to use the \f(CW\*(C`HASH\*(C'\fR option
(see above) to request that \f(CW\*(C`Memoize\*(C'\fR use a particular hash variable
as its cache.  Then you can examine or modify the hash at any time in
any way you desire.  You may flush the cache by using \f(CW\*(C`%hash = ()\*(C'\fR. 
.SH "CAVEATS"
.IX Header "CAVEATS"
Memoization is not a cure\-all:
.IP "\(bu" 4
Do not memoize a function whose behavior depends on program
state other than its own arguments, such as global variables, the time
of day, or file input.  These functions will not produce correct
results when memoized.  For a particularly easy example:
.Sp
.Vb 3
\&        sub f {
\&          time;
\&        }
.Ve
.Sp
This function takes no arguments, and as far as \f(CW\*(C`Memoize\*(C'\fR is
concerned, it always returns the same result.  \f(CW\*(C`Memoize\*(C'\fR is wrong, of
course, and the memoized version of this function will call \f(CW\*(C`time\*(C'\fR once
to get the current time, and it will return that same time
every time you call it after that.
.IP "\(bu" 4
Do not memoize a function with side effects.
.Sp
.Vb 5
\&        sub f {
\&          my ($a, $b) = @_;
\&          my $s = $a + $b;
\&          print "$a + $b = $s.\en";
\&        }
.Ve
.Sp
This function accepts two arguments, adds them, and prints their sum.
Its return value is the numuber of characters it printed, but you
probably didn't care about that.  But \f(CW\*(C`Memoize\*(C'\fR doesn't understand
that.  If you memoize this function, you will get the result you
expect the first time you ask it to print the sum of 2 and 3, but
subsequent calls will return 1 (the return value of
\&\f(CW\*(C`print\*(C'\fR) without actually printing anything.
.IP "\(bu" 4
Do not memoize a function that returns a data structure that is
modified by its caller.
.Sp
Consider these functions:  \f(CW\*(C`getusers\*(C'\fR returns a list of users somehow,
and then \f(CW\*(C`main\*(C'\fR throws away the first user on the list and prints the
rest:
.Sp
.Vb 7
\&        sub main {
\&          my $userlist = getusers();
\&          shift @$userlist;
\&          foreach $u (@$userlist) {
\&            print "User $u\en";
\&          }
\&        }
.Ve
.Sp
.Vb 5
\&        sub getusers {
\&          my @users;
\&          # Do something to get a list of users;
\&          \e@users;  # Return reference to list.
\&        }
.Ve
.Sp
If you memoize \f(CW\*(C`getusers\*(C'\fR here, it will work right exactly once.  The
reference to the users list will be stored in the memo table.  \f(CW\*(C`main\*(C'\fR
will discard the first element from the referenced list.  The next
time you invoke \f(CW\*(C`main\*(C'\fR, \f(CW\*(C`Memoize\*(C'\fR will not call \f(CW\*(C`getusers\*(C'\fR; it will
just return the same reference to the same list it got last time.  But
this time the list has already had its head removed; \f(CW\*(C`main\*(C'\fR will
erroneously remove another element from it.  The list will get shorter
and shorter every time you call \f(CW\*(C`main\*(C'\fR.
.Sp
Similarly, this:
.Sp
.Vb 3
\&        $u1 = getusers();    
\&        $u2 = getusers();    
\&        pop @$u1;
.Ve
.Sp
will modify \f(CW$u2\fR as well as \f(CW$u1\fR, because both variables are references
to the same array.  Had \f(CW\*(C`getusers\*(C'\fR not been memoized, \f(CW$u1\fR and \f(CW$u2\fR
would have referred to different arrays.
.IP "\(bu" 4
Do not memoize a very simple function.
.Sp
Recently someone mentioned to me that the Memoize module made his
program run slower instead of faster.  It turned out that he was
memoizing the following function:
.Sp
.Vb 3
\&    sub square {
\&      $_[0] * $_[0];
\&    }
.Ve
.Sp
I pointed out that \f(CW\*(C`Memoize\*(C'\fR uses a hash, and that looking up a
number in the hash is necessarily going to take a lot longer than a
single multiplication.  There really is no way to speed up the
\&\f(CW\*(C`square\*(C'\fR function.
.Sp
Memoization is not magical.
.SH "PERSISTENT CACHE SUPPORT"
.IX Header "PERSISTENT CACHE SUPPORT"
You can tie the cache tables to any sort of tied hash that you want
to, as long as it supports \f(CW\*(C`TIEHASH\*(C'\fR, \f(CW\*(C`FETCH\*(C'\fR, \f(CW\*(C`STORE\*(C'\fR, and
\&\f(CW\*(C`EXISTS\*(C'\fR.  For example,
.PP
.Vb 2
\&        tie my %cache => 'GDBM_File', $filename, O_RDWR|O_CREAT, 0666;
\&        memoize 'function', SCALAR_CACHE => [HASH => \e%cache];
.Ve
.PP
works just fine.  For some storage methods, you need a little glue.
.PP
\&\f(CW\*(C`SDBM_File\*(C'\fR doesn't supply an \f(CW\*(C`EXISTS\*(C'\fR method, so included in this
package is a glue module called \f(CW\*(C`Memoize::SDBM_File\*(C'\fR which does
provide one.  Use this instead of plain \f(CW\*(C`SDBM_File\*(C'\fR to store your
cache table on disk in an \f(CW\*(C`SDBM_File\*(C'\fR database:
.PP
.Vb 2
\&        tie my %cache => 'Memoize::SDBM_File', $filename, O_RDWR|O_CREAT, 0666;
\&        memoize 'function', SCALAR_CACHE => [HASH => \e%cache];
.Ve
.PP
\&\f(CW\*(C`NDBM_File\*(C'\fR has the same problem and the same solution.  (Use
\&\f(CW\*(C`Memoize::NDBM_File instead of plain NDBM_File.\*(C'\fR)
.PP
\&\f(CW\*(C`Storable\*(C'\fR isn't a tied hash class at all.  You can use it to store a
hash to disk and retrieve it again, but you can't modify the hash while
it's on the disk.  So if you want to store your cache table in a
\&\f(CW\*(C`Storable\*(C'\fR database, use \f(CW\*(C`Memoize::Storable\*(C'\fR, which puts a hashlike
front-end onto \f(CW\*(C`Storable\*(C'\fR.  The hash table is actually kept in
memory, and is loaded from your \f(CW\*(C`Storable\*(C'\fR file at the time you
memoize the function, and stored back at the time you unmemoize the
function (or when your program exits):
.PP
.Vb 2
\&        tie my %cache => 'Memoize::Storable', $filename;
\&        memoize 'function', SCALAR_CACHE => [HASH => \e%cache];
.Ve
.PP
.Vb 2
\&        tie my %cache => 'Memoize::Storable', $filename, 'nstore';
\&        memoize 'function', SCALAR_CACHE => [HASH => \e%cache];
.Ve
.PP
Include the `nstore' option to have the \f(CW\*(C`Storable\*(C'\fR database written
in `network order'.  (See Storable for more details about this.)
.PP
The \f(CW\*(C`flush_cache()\*(C'\fR function will raise a run-time error unless the
tied package provides a \f(CW\*(C`CLEAR\*(C'\fR method.
.SH "EXPIRATION SUPPORT"
.IX Header "EXPIRATION SUPPORT"
See Memoize::Expire, which is a plug-in module that adds expiration
functionality to Memoize.  If you don't like the kinds of policies
that Memoize::Expire implements, it is easy to write your own plug-in
module to implement whatever policy you desire.  Memoize comes with
several examples.  An expiration manager that implements a \s-1LRU\s0 policy
is available on \s-1CPAN\s0 as Memoize::ExpireLRU.
.SH "BUGS"
.IX Header "BUGS"
The test suite is much better, but always needs improvement.
.PP
There is some problem with the way \f(CW\*(C`goto &f\*(C'\fR works under threaded
Perl, perhaps because of the lexical scoping of \f(CW@_\fR.  This is a bug
in Perl, and until it is resolved, memoized functions will see a
slightly different \f(CW\*(C`caller()\*(C'\fR and will perform a little more slowly
on threaded perls than unthreaded perls.
.PP
Some versions of \f(CW\*(C`DB_File\*(C'\fR won't let you store data under a key of
length 0.  That means that if you have a function \f(CW\*(C`f\*(C'\fR which you
memoized and the cache is in a \f(CW\*(C`DB_File\*(C'\fR database, then the value of
\&\f(CW\*(C`f()\*(C'\fR (\f(CW\*(C`f\*(C'\fR called with no arguments) will not be memoized.  If this
is a big problem, you can supply a normalizer function that prepends
\&\f(CW"x"\fR to every key.
.SH "MAILING LIST"
.IX Header "MAILING LIST"
To join a very low-traffic mailing list for announcements about
\&\f(CW\*(C`Memoize\*(C'\fR, send an empty note to \f(CW\*(C`mjd\-perl\-memoize\-request@plover.com\*(C'\fR.
.SH "AUTHOR"
.IX Header "AUTHOR"
Mark-Jason Dominus (\f(CW\*(C`mjd\-perl\-memoize+@plover.com\*(C'\fR), Plover Systems co.
.PP
See the \f(CW\*(C`Memoize.pm\*(C'\fR Page at http://www.plover.com/~mjd/perl/Memoize/
for news and upgrades.  Near this page, at
http://www.plover.com/~mjd/perl/MiniMemoize/ there is an article about
memoization and about the internals of Memoize that appeared in The
Perl Journal, issue #13.  (This article is also included in the
Memoize distribution as `article.html'.)
.PP
My upcoming book will discuss memoization (and many other fascinating
topics) in tremendous detail.  It will be published by Morgan Kaufmann
in 2002, possibly under the title \fIPerl Advanced Techniques
Handbook\fR.  It will also be available on-line for free.  For more
information, visit http://perl.plover.com/book/ .
.PP
To join a mailing list for announcements about \f(CW\*(C`Memoize\*(C'\fR, send an
empty message to \f(CW\*(C`mjd\-perl\-memoize\-request@plover.com\*(C'\fR.  This mailing
list is for announcements only and has extremely low traffic\-\-\-about
two messages per year.
.SH "COPYRIGHT AND LICENSE"
.IX Header "COPYRIGHT AND LICENSE"
Copyright 1998, 1999, 2000, 2001  by Mark Jason Dominus
.PP
This library is free software; you may redistribute it and/or modify
it under the same terms as Perl itself.
.SH "THANK YOU"
.IX Header "THANK YOU"
Many thanks to Jonathan Roy for bug reports and suggestions, to
Michael Schwern for other bug reports and patches, to Mike Cariaso for
helping me to figure out the Right Thing to Do About Expiration, to
Joshua Gerth, Joshua Chamas, Jonathan Roy (again), Mark D. Anderson,
and Andrew Johnson for more suggestions about expiration, to Brent
Powers for the Memoize::ExpireLRU module, to Ariel Scolnicov for
delightful messages about the Fibonacci function, to Dion Almaer for
thought-provoking suggestions about the default normalizer, to Walt
Mankowski and Kurt Starsinic for much help investigating problems
under threaded Perl, to Alex Dudkevich for reporting the bug in
prototyped functions and for checking my patch, to Tony Bass for many
helpful suggestions, to Jonathan Roy (again) for finding a use for
\&\f(CW\*(C`unmemoize()\*(C'\fR, to Philippe Verdret for enlightening discussion of
\&\f(CW\*(C`Hook::PrePostCall\*(C'\fR, to Nat Torkington for advice I ignored, to Chris
Nandor for portability advice, to Randal Schwartz for suggesting the
\&'\f(CW\*(C`flush_cache\*(C'\fR function, and to Jenda Krynicky for being a light in
the world.
.PP
Special thanks to Jarkko Hietaniemi, the 5.8.0 pumpking, for including
this module in the core and for his patient and helpful guidance
during the integration process.

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.