Created
July 17, 2018 20:10
-
-
Save rust-play/5aac63fed8def7ae744c0ea783ab6883 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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; | |
pub struct CacheMap<F, T, V> | |
where F: Fn(&T) -> V, T: Hash + Eq + Copy, V: Copy | |
{ | |
operation: F, | |
results: HashMap<T, V>, | |
} | |
impl<F, T, V> CacheMap<F, T, V> | |
where F: Fn(&T) -> V, T: Hash + Eq + Copy, V: Copy | |
{ | |
pub fn new(f: F) -> CacheMap<F, T, V> { | |
CacheMap { | |
operation: f, | |
results: HashMap::new(), | |
} | |
} | |
pub fn value (&mut self, arg: &T) -> V { | |
match self.results.get(arg) { | |
Some(val) => *val, | |
None => { | |
let val = (self.operation)(arg); | |
self.results.insert(*arg, val); | |
val | |
} | |
} | |
} | |
} | |
fn main() {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment