Memoizer
This struct allows you to memoize the results of a deterministic, pure functions to save computational resources on repeated function calls. A better version of this library exists here.
Quickstart
Add the following to your Cargo.toml:
[]
= "0.2.2"
Add the following to your main/lib.rs:
use Memoizer;
This prints:
Examples
Trivial Expensive Function
The difficult(n: usize)
function simulates a computationally expensive function. It taks about a 20th of a second to run and returns nothing. When called 500 times with random inputs (limited [0,9))it takes about ~2.5 seconds. When using the Memoizer struct it takes ~0.05 seconds.
use sleep;
use ;
use Rng;
use Memoizer;
// Expensive Calculation
This prints:
Function Signature
The closure provided to the Memoize struct must take a single parameter and return a single value. Passing structs, references and heap allocated parameters is fine, but make sure they implement: Eq, Hash, Clone so they can be used as keys in the HashMap. Fortunately, most of these traits can be derived for complex types.
The return value must implement the Clone trait so that the value in the HashMap cannot be corrupted.
Here's an example using a struct as the input parameter and returning a number.
use Memoizer;
/* Dummy struct to test more complex inputs/returns */
/* PartialEq & Eq required for HashMap */
Future Work
Currently, there is no ability to memoize recursive functions, which is unfortunate because dynamic programming is where a memoizer would really shine and they often employ recursion. Look for this in v0.3.0.