Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <map>
- #include <cassert>
- #include <typeinfo>
- #include <functional>
- #include <unistd.h>
- using std::cout;
- namespace category2 {
- /*
- * Define a higher-order function (or a function object) memoize in your favorite language. This function takes a
- * pure function f as an argument and returns a function that behaves almost exactly like f, except that it only
- * calls the original function once for every argument, stores the result internally, and subsequently returns this
- * stored result every time it’s called with the same argument.
- *
- * You can tell the memoized function from the original by watching its performance. For instance, try to memoize a
- * function that takes a long time to evaluate. You’ll have to wait for the result the first time you call it, but
- * on subsequent calls, with the same argument, you should get the result immediately.
- * */
- template <typename T>
- class Memoize{
- std::map<int, int> calculated;
- public:
- T operator() (const T& i, std::function<int(int)>& fun){
- //cout << i;
- //cout << fun(i);
- try {
- return calculated.at(i);
- }catch (std::out_of_range& e){
- std::cout << "memoize " << i << "\n";
- calculated[i] = fun(i);
- return calculated.at(i);
- }
- }
- };
- void run(){
- std::vector<int> results;
- std::function<int(int)> f_sum = [] (int i) -> int { sleep(3); return i*2; };
- Memoize<int> m;
- std::cout << m(3, f_sum) << "\n";
- std::cout << m(4, f_sum) << "\n";;
- std::cout << m(4, f_sum) << "\n";;
- std::cout << m(2, f_sum) << "\n";;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement