monad.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright Louis Dionne 2013-2017
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
  4. #include <boost/hana/assert.hpp>
  5. #include <boost/hana/chain.hpp>
  6. #include <boost/hana/eval.hpp>
  7. #include <boost/hana/lazy.hpp>
  8. #include <functional>
  9. #include <iostream>
  10. #include <sstream>
  11. namespace hana = boost::hana;
  12. template <typename T>
  13. T read_(std::istream& stream) {
  14. T x;
  15. stream >> x;
  16. std::cout << "read " << x << " from the stream\n";
  17. return x;
  18. }
  19. int main() {
  20. std::stringstream ss;
  21. int in = 123;
  22. std::cout << "creating the monadic chain...\n";
  23. auto out = hana::make_lazy(read_<int>)(std::ref(ss))
  24. | [](auto x) {
  25. std::cout << "performing x + 1...\n";
  26. return hana::make_lazy(x + 1);
  27. }
  28. | [](auto x) {
  29. std::cout << "performing x / 2...\n";
  30. return hana::make_lazy(x / 2);
  31. };
  32. std::cout << "putting " << in << " in the stream...\n";
  33. ss << in; // nothing is evaluated yet
  34. std::cout << "evaluating the monadic chain...\n";
  35. auto eout = hana::eval(out);
  36. std::cout << "the result of the monadic chain is " << eout << "\n";
  37. BOOST_HANA_RUNTIME_CHECK(eout == (in + 1) / 2);
  38. }