Created
October 8, 2021 08:15
-
-
Save darotar/23a3d55ff543b880fb0260c13d7f0cba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashMap; | |
use std::hash::Hash; | |
struct Cacher<T, U, V> | |
where | |
T: Fn(U) -> V, | |
U: Hash + Eq + Clone, | |
V: Copy, | |
{ | |
calculation: T, | |
values: HashMap<U, V>, | |
} | |
impl<T, U, V> Cacher<T, U, V> | |
where | |
T: Fn(U) -> V, | |
U: Hash + Eq + Clone, | |
V: Copy, | |
{ | |
fn new(calculation: T) -> Cacher<T, U, V> { | |
Cacher { | |
calculation, | |
values: HashMap::new(), | |
} | |
} | |
fn value(&mut self, arg: U) -> V { | |
match self.values.get(&arg).map(|v| v.clone()) { | |
Some(v) => v, | |
None => { | |
let v: V = (self.calculation)(arg.clone()); | |
self.values.insert(arg, v.clone()); | |
v | |
} | |
} | |
} | |
} | |
fn main() { | |
let mut cacher = Cacher::new(|i: i32| i + 10); | |
println!("{}", cacher.value(10)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment