foldable.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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/first.hpp>
  6. #include <boost/hana/fold_left.hpp>
  7. #include <boost/hana/insert.hpp>
  8. #include <boost/hana/integral_constant.hpp>
  9. #include <boost/hana/map.hpp>
  10. #include <boost/hana/pair.hpp>
  11. #include <boost/hana/second.hpp>
  12. #include <boost/hana/type.hpp>
  13. namespace hana = boost::hana;
  14. int main() {
  15. // Given a map of (key, value) pairs, returns a map of (value, key) pairs.
  16. // This requires both the keys and the values to be compile-time Comparable.
  17. auto invert = [](auto map) {
  18. return hana::fold_left(map, hana::make_map(), [](auto map, auto pair) {
  19. return hana::insert(map, hana::make_pair(hana::second(pair), hana::first(pair)));
  20. });
  21. };
  22. auto m = hana::make_map(
  23. hana::make_pair(hana::type_c<int>, hana::int_c<1>),
  24. hana::make_pair(hana::type_c<float>, hana::int_c<2>),
  25. hana::make_pair(hana::int_c<3>, hana::type_c<void>)
  26. );
  27. BOOST_HANA_CONSTANT_CHECK(invert(m) ==
  28. hana::make_map(
  29. hana::make_pair(hana::int_c<1>, hana::type_c<int>),
  30. hana::make_pair(hana::int_c<2>, hana::type_c<float>),
  31. hana::make_pair(hana::type_c<void>, hana::int_c<3>)
  32. )
  33. );
  34. }