Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::HashMap;
- struct Cacher<T, U, F> {
- values: HashMap<T, U>,
- calculation: F,
- }
- impl<T: std::cmp::Eq + std::hash::Hash, U, F> Cacher<T, U, F> {
- fn new(calculation: impl Fn(T) -> U) -> Cacher<T, U, F> {
- let hash: HashMap<T, U> = HashMap::new();
- Cacher { values: hash, calculation: calculation }
- }
- fn value(&mut self, arg: T) -> U {
- match self.values.get(&arg) {
- Some(&cached) => cached,
- None => {
- let value = (self.calculation)(arg);
- self.values.insert(arg, value);
- value
- }
- }
- }
- }
- fn main() {
- let mut calculator = Cacher::new(|n| n + 1);
- println!("value: {}", calculator.value(5));
- println!("value: {}", calculator.value(200));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement