Skip to content

Instantly share code, notes, and snippets.

@tmiller
Created July 22, 2017 01:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmiller/a585dfb8ea7dfee52f72d56757a9dbfc to your computer and use it in GitHub Desktop.
Save tmiller/a585dfb8ea7dfee52f72d56757a9dbfc to your computer and use it in GitHub Desktop.
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