Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 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. let hash: HashMap<T, U> = HashMap::new();
  11. Cacher { values: hash, calculation: calculation }
  12. }
  13.  
  14. fn value(&mut self, arg: T) -> U {
  15. match self.values.get(&arg) {
  16. Some(&cached) => cached,
  17. None => {
  18. let value = (self.calculation)(arg);
  19. self.values.insert(arg, value);
  20. value
  21. }
  22. }
  23. }
  24. }
  25.  
  26. fn main() {
  27. let mut calculator = Cacher::new(|n| n + 1);
  28. println!("value: {}", calculator.value(5));
  29. println!("value: {}", calculator.value(200));
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement