Advertisement
Guest User

Untitled

a guest
May 27th, 2015
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. //C++11
  2. #include <functional>
  3. #include <map>
  4.  
  5. template<typename... Args, typename T,
  6. typename R = std::result_of_t<std::decay_t<T>(Args...)>>
  7. auto memoize(T&& f) -> std::function<R(Args...)>
  8. {
  9. //use "move capture" in C++14
  10. auto const p = new std::map<std::tuple<Args...>, R>();
  11. return ([f, p](Args... args) -> R {
  12. auto&& t = std::make_tuple(args...);
  13. auto it = p->find(t);
  14. if ( it == p->end() ) { it = p->emplace(it, std::move(t), f(std::forward<Args>(args)...)); }
  15. return it->second;
  16. });
  17. }
  18.  
  19. //---------------
  20. // sample
  21.  
  22. #include <iostream>
  23. using namespace std;
  24.  
  25. // Fibonacci
  26. static auto fib = memoize<int>([](int n) {
  27. cout << "fib(" << n << ")" << endl;
  28. if ( n == 0 ) return 0;
  29. if ( n == 1 ) return 1;
  30. return fib(n - 1) + fib(n - 2);
  31. });
  32.  
  33. // function with arity 3
  34. static auto g = memoize<double, double, double>([](double x, double y, double z) {
  35. cout << "g" << endl;
  36. return x + y + z;
  37. });
  38.  
  39. int main() {
  40. cout << fib(30) << endl;
  41. //invoke fib(n) only once for each n (= 30, 29, ..., 2, 1)
  42.  
  43. for (int i = 0; i < 2; ++i) {
  44. cout << g(1.0, 2.0, 3.0) << endl;
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement