daily pastebin goal
47%
SHARE
TWEET

Untitled

a guest Jan 17th, 2019 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::thread;
  2. use std::time::Duration;
  3.  
  4. fn main() {
  5.   let simulated_user_specified_value = 10;
  6.   let simulated_random_number = 5;
  7.  
  8.   generate_workout(simulated_user_specified_value, simulated_random_number);
  9. }
  10.  
  11. fn generate_workout(intensity: u32, random_number: u32) {
  12.   let mut expensive_result = Cacher::new(|num| {
  13.     println!("calculating slowly...");
  14.     thread::sleep(Duration::from_secs(2));
  15.     num
  16.   });
  17.   if intensity < 25 {
  18.     println!("Today, do {} pushups!", expensive_result.value(intensity));
  19.     println!("Next, do {} situps!", expensive_result.value(intensity));
  20.   } else {
  21.     if random_number == 3 {
  22.       println!("Take a break today! Remember to stay hydrated!");
  23.     } else {
  24.       println!("Today, run for {} minutes!", expensive_result.value(intensity));
  25.     }
  26.   }
  27. }
  28.  
  29. struct Cacher<T, U>
  30.   where T: Fn(U) -> U
  31. {
  32.   calculation: T,
  33.   value: Option<U>,
  34. }
  35.  
  36. impl <T, U> Cacher<T, U>
  37.   where T: Fn(U) -> U
  38. {
  39.   fn new(calculation: T) -> Cacher<T, U> {
  40.     Cacher {
  41.       calculation,
  42.       value: None,
  43.     }
  44.   }
  45.   fn value(&mut self, arg: U) -> U {
  46.     match self.value {
  47.       Some(v) => {
  48.         if v == arg {
  49.           v
  50.         } else {
  51.           let v = (self.calculation)(arg);
  52.           self.value = Some(v);
  53.           v
  54.         }
  55.       },
  56.       None => {
  57.         let v = (self.calculation)(arg);
  58.         self.value = Some(v);
  59.         v
  60.       }
  61.     }
  62.   }
  63. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top