Guest User

Untitled

a guest
Jan 16th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use std::hash::Hash;
  3.  
  4. pub struct Cache<K, V, F> {
  5. cache: HashMap<K, V>,
  6. compute: F,
  7. }
  8.  
  9. impl<'a, K, V, F> Cache<K, V, F>
  10. where
  11. K: Hash + Eq + Copy,
  12. V: Copy,
  13. F: Fn(K, &mut dyn FnMut(K) -> V) -> V,
  14. {
  15. pub fn new(compute: F) -> Cache<K, V, F> {
  16. let cache = HashMap::new();
  17. Cache { cache, compute }
  18. }
  19.  
  20. pub fn get(&mut self, key: K) -> V {
  21. get(&mut self.cache, &self.compute, key)
  22. }
  23. }
  24.  
  25. fn get<'a, K, V, F>(cache: &mut HashMap<K, V>, f: &F, key: K) -> V
  26. where
  27. K: Hash + Eq + Copy,
  28. V: Copy,
  29. F: Fn(K, &mut dyn FnMut(K) -> V) -> V,
  30. {
  31. if let Some(&value) = cache.get(&key) {
  32. return value;
  33. }
  34.  
  35. let value = (f)(key, &mut |k: K| get(cache, f, k));
  36. cache.insert(key, value);
  37. value
  38. }
  39.  
  40. fn main() {
  41. let mut fib = Cache::new(
  42. |n: usize, fib| {
  43. if n <= 1 {
  44. n
  45. } else {
  46. fib(n - 1) + fib(n - 2)
  47. }
  48. },
  49. );
  50. println!("fib80 = {}", fib.get(80));
  51. }
Add Comment
Please, Sign In to add comment