Created
July 22, 2017 01:05
-
-
Save tmiller/a585dfb8ea7dfee52f72d56757a9dbfc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
struct Catcher<K, V, T> | |
where | |
K: Eq + Hash + Copy, | |
V: Copy, | |
T: Fn(K) -> V | |
{ | |
calculation: T, | |
cache: HashMap<K, V>, | |
} | |
impl<K, V, T> Catcher<K, V, T> | |
where | |
K: Eq + Hash + Copy, | |
V: Copy, | |
T: Fn(K) -> V | |
{ | |
fn new(calculation: T) -> Catcher<K, V, T> { | |
Catcher { | |
calculation, | |
cache: HashMap::new(), | |
} | |
} | |
fn value(&mut self, arg: K) -> V { | |
if let Some(v) = self.cache.get(&arg) { | |
return *v | |
} | |
let v = (self.calculation)(arg); | |
self.cache.insert(arg, v); | |
v | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment