\HeaderA{cache}{Evaluate an expression if its value is not already cached.}{cache}
\keyword{manip}{cache}
\keyword{array}{cache}
\begin{Description}\relax
Cache the evaluation of an expression in the file system.
\end{Description}
\begin{Usage}
\begin{verbatim}
    cache(expr, dir=".", prefix="tmp_R_cache_", name)
\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{expr}] An expression of the form \code{LHS <- RHS}, Where
\code{LHS} is a variable name, \code{RHS} is any valid expression,
and \code{<-} must be used (\code{=} will not work).
\item[\code{dir}] A string specifying the directory into which cache files
should be written (also where to go searching for an appropriate
cache file).
\item[\code{prefix}] A string giving the prefix to use when naming and
searching for cache files.  The default is \code{"tmp\_R\_cache\_"}
\item[\code{name}] Unused.  This argument is present as a compatibility
layer for the deprecated calling convention.
\end{ldescription}
\end{Arguments}
\begin{Details}\relax
This function can be useful during the development of computationally
intensive workflows, for example in vignettes or scripts.  The
function uses a cache file in \code{dir} which defaults to the current
working directory whose name is obtained by \code{paste(prefix, name,
  ".RData", sep="")}.

When \code{cache} is called and the cache file exists, it is loaded
and the object whose name is given on the left of \code{<-} in
\code{expr} is returned.  In this case, \code{expr} is \emph{not}
evaluted.

When \code{cache} is called and the cache file does not exist,
\code{expr} is evaluted, its value is saved into a cache file, and
then its value is returned.

The \code{expr} argument must be of the form of \code{someVar <-
    \{expressions\}}.  That is, the left hand side must be a single symbol
name and the next syntactic token must be \code{<-}.

To flush the cache and force recomputation, simply remove the cache
files.  You can use \code{\LinkA{file.remove}{file.remove}} to do this.
\end{Details}
\begin{Value}
The (cached) value of \code{expr}.
\end{Value}
\begin{Section}{Note}
The first version of this function had a slightly different interface
which is now deprecated (but still functional).  The old version has
arguments \code{name} and \code{expr} and the intended usage is:
\code{foo <- cache("foo", expr)}.
\end{Section}
\begin{Author}\relax
Wolfgang Huber, \email{huber@ebi.ac.uk}
Seth Falcon, \email{sfalcon@fhcrc.org}
\end{Author}
\begin{Examples}
\begin{ExampleCode}
    bigCalc <- function() runif(10)
    cache(myComplicatedObject <- bigCalc())
    aCopy <- myComplicatedObject
    remove(myComplicatedObject)
    cache(myComplicatedObject <- bigCalc())
    stopifnot(all.equal(myComplicatedObject, aCopy))
    allCacheFiles <- list.files(".", pattern="^tmp_R_cache_.*\.RData$",
                                full.name=TRUE)
    file.remove(allCacheFiles)
\end{ExampleCode}
\end{Examples}

