diff options
-rw-r--r-- | README.rst | 29 | ||||
-rw-r--r-- | test.cpp | 16 | ||||
-rw-r--r-- | test_ref.txt | 1 |
3 files changed, 46 insertions, 0 deletions
@@ -14,6 +14,35 @@ the underlying `any` type, an exception will be thrown when the resolved value types do not match the types expected in the subsequent computation. See `test.cpp` for detailed examples. +Example +======= + +Calculate the factorial of n, the hard way: + +.. code-block:: cpp + + #include "promise.hpp" + + using promise::promise_t; + + int main() { + promise_t root; + promise_t t = root; + for (int i = 0; i < 10; i++) + t = t.then([](std::pair<int, int> p) { + p.first *= p.second; + p.second++; + return p; + }); + t.then([](std::pair<int, int> p) { + printf("fac(%d) = %d\n", p.second, p.first); + }); + /* no actual calculation until here */ + root.resolve(std::make_pair(1, 1)); + return 0; + } + + API === @@ -30,6 +30,21 @@ promise_t g(int x) { return promise_t([](promise_t pm) {pm.resolve(1);}); } +void test_fac() { + promise_t root; + promise_t t = root; + for (int i = 0; i < 10; i++) + t = t.then([](std::pair<int, int> p) { + p.first *= p.second; + p.second++; + return p; + }); + t.then([](std::pair<int, int> p) { + printf("fac(%d) = %d\n", p.second, p.first); + }); + root.resolve(std::make_pair(1, 1)); +} + int main() { callback_t t1; callback_t t2; @@ -143,4 +158,5 @@ int main() { t1(); puts("calling t2: resolve the second half of promise 1 (promise 2)"); t2(); + test_fac(); } diff --git a/test_ref.txt b/test_ref.txt index 574a8b3..40d1b22 100644 --- a/test_ref.txt +++ b/test_ref.txt @@ -27,3 +27,4 @@ promise 9 resolved with 101 rejecting with value -1 reason: -1 reason: 0 +fac(11) = 3628800 |