Skip to content

Instantly share code, notes, and snippets.

@nulltier
Created February 8, 2022 22:35
Show Gist options
  • Save nulltier/e664a3d87f3cca44ae03de61ee9d48cc to your computer and use it in GitHub Desktop.
Save nulltier/e664a3d87f3cca44ae03de61ee9d48cc to your computer and use it in GitHub Desktop.
Rust function with memoization
struct Memoize<'a, A, R> {
cache: std::collections::HashMap<A, R>,
func: &'a dyn Fn(A) -> R
}
impl<'a, A, R> Memoize<'a, A, R> where
A: Eq + std::hash::Hash + Copy + Clone,
R: Copy + Clone
{
fn from_func(func: &'a dyn Fn(A) -> R) -> Self {
Self {
cache: std::collections::HashMap::<A, R>::new(),
func,
}
}
fn call(&mut self, arg: A) -> R {
match self.cache.get(&arg) {
Some(result) => {
*result
},
None => {
let result = (self.func)(arg);
self.cache.insert(arg, result);
result
}
}
}
}
fn mul_100(input: i64) -> i64 {
println!("CALCULATE: {} -> {}", input, input * 100);
input * 100
}
fn main() {
println!("start");
let mut mul_100_memo = Memoize::from_func(&mul_100);
// .call() is needed because the FnMut and FnOnce traits works only in nightly builds
println!("1: {}", mul_100_memo.call(100));
println!("1: {}", mul_100_memo.call(101));
println!("1: {}", mul_100_memo.call(102));
println!("1: {}", mul_100_memo.call(102));
println!("1: {}", mul_100_memo.call(100));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment