Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. use std::collections::HashMap;
  2.  
  3. struct Cacher<T, U, F> {
  4. values: HashMap<T, U>,
  5. calculation: F,
  6. }
  7.  
  8. impl<T: std::cmp::Eq + std::hash::Hash, U, F> Cacher<T, U, F> {
  9. fn new(calculation: impl Fn(T) -> U) -> Cacher<T, U, F> {
  10. Cacher { values: HashMap::new(), calculation: calculation }
  11. }
  12.  
  13. fn value(&mut self, arg: T) -> U {
  14. match self.values.get(&arg) {
  15. Some(&cached) => cached,
  16. None => {
  17. let value = (self.calculation)(arg);
  18. self.values.insert(arg, value);
  19. value
  20. }
  21. }
  22. }
  23. }
  24.  
  25. fn main() {
  26. let mut calculator = Cacher::new(|n| n + 1);
  27. println!("value: {}", calculator.value(5));
  28. println!("value: {}", calculator.value(200));
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement