Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2016
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <cassert>
  4. #include <typeinfo>
  5. #include <functional>
  6. #include <unistd.h>
  7. using std::cout;
  8.  
  9.  
  10.  
  11. namespace category2 {
  12.     /*
  13.      * Define a higher-order function (or a function object) memoize in your favorite language. This function takes a
  14.      * pure function f as an argument and returns a function that behaves almost exactly like f, except that it only
  15.      * calls the original function once for every argument, stores the result internally, and subsequently returns this
  16.      * stored result every time it’s called with the same argument.
  17.      *
  18.      * You can tell the memoized function from the original by watching its performance. For instance, try to memoize a
  19.      * function that takes a long time to evaluate. You’ll have to wait for the result the first time you call it, but
  20.      * on subsequent calls, with the same argument, you should get the result immediately.
  21.      * */
  22.  
  23.     template <typename T>
  24.     class Memoize{
  25.         std::map<int, int> calculated;
  26.     public:
  27.         T operator() (const T& i, std::function<int(int)>& fun){
  28.             //cout << i;
  29.             //cout << fun(i);
  30.             try {
  31.                 return calculated.at(i);
  32.             }catch (std::out_of_range& e){
  33.                 std::cout << "memoize " << i << "\n";
  34.                 calculated[i] = fun(i);
  35.                 return calculated.at(i);
  36.             }
  37.         }
  38.     };
  39.  
  40.     void run(){
  41.         std::vector<int> results;
  42.         std::function<int(int)> f_sum =  [] (int i)  -> int { sleep(3); return i*2; };
  43.  
  44.         Memoize<int> m;
  45.         std::cout << m(3, f_sum) << "\n";
  46.         std::cout << m(4, f_sum) << "\n";;
  47.         std::cout << m(4, f_sum) << "\n";;
  48.         std::cout << m(2, f_sum) << "\n";;
  49.  
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement