One rather complex procedure is cache
, which creates a procedure that generates and caches a value. cache
takes a function to generate the cache lifetime, as well as a function to generate the value to cache.
The value function is executed the first time the created procedure is called, and will be executed again only if the created procedure is called when the cache lifetime has expired. Otherwise, the cached value is returned. Typically a cache is used when the value function is something expensive to evaluate.
The motivation behind dynamically computing the cache lifetime is that the lifetime can be modified for an existing cache, for instance through a global variable.
arc> (= mycache (cache (fn () 10) (fn () (prn "evaluated") (tostring (system "date"))))) #<procedure> arc> (mycache) evaluated "Mon Mar 10 21:08:33 PDT 2008\n" arc> (mycache) "Mon Mar 10 21:08:33 PDT 2008\n" arc> (mycache) evaluated "Mon Mar 10 21:08:46 PDT 2008\n"
Copyright 2008 Ken Shirriff.