foldl.qbk 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. [#foldl]
  2. [section foldl]
  3. [h1 Synopsis]
  4. template <class P, class State, class ForwardOp>
  5. struct foldl;
  6. This is a [link parser_combinator parser combinator].
  7. [table Arguments
  8. [[Name] [Type]]
  9. [[`P`] [[link parser parser]]]
  10. [[`State`] [[link metaprogramming_value template metaprogramming value]]]
  11. [[`ForwardOp`] [[link metafunction_class template metafunction class] taking two arguments]]
  12. ]
  13. [h1 Description]
  14. `foldl` applies `P` on the input string repeatedly as long as `P` accepts the
  15. input. The result of parsing is equivalent to
  16. `boost::mpl::fold<Sequence, State, ForwardOp>`, where `Sequence` is the sequence
  17. of the results of the applications of `P`.
  18. When `P` rejects the input for the first time, `foldl` still accepts the input
  19. and the result of parsing is `State`.
  20. Here is a diagram showing how `foldl` works by example:
  21. using int_token = token<int_>;
  22. using sum_op = mpl::lambda<mpl::plus<mpl::_1, mpl::_2>>::type;
  23. [$images/metaparse/foldl_diag2.png [width 70%]]
  24. Further details can be found in the [link introducing-foldl Introducing foldl]
  25. section of the [link manual User Manual].
  26. [h1 Header]
  27. #include <boost/metaparse/foldl.hpp>
  28. [h1 Expression semantics]
  29. For any `p` parser, `t` class, `f` metafunction class taking two arguments,
  30. `s` compile-time string and `pos` source position
  31. foldl<p, t, f>::apply<s, pos>
  32. is equivalent to
  33. return_<t>::apply<s, pos>
  34. when `p::apply<s, pos>` returns an error. It is
  35. foldl<p, f::apply<t, get_result<p::apply<s, pos>>::type>::type, f>::apply<
  36. get_remaining<p::apply<s, pos>>,
  37. get_position<p::apply<s, pos>>
  38. >
  39. otherwise.
  40. [h1 Example]
  41. #include <boost/metaparse/foldl.hpp>
  42. #include <boost/metaparse/token.hpp>
  43. #include <boost/metaparse/int_.hpp>
  44. #include <boost/metaparse/string.hpp>
  45. #include <boost/metaparse/start.hpp>
  46. #include <boost/metaparse/get_result.hpp>
  47. #include <boost/mpl/lambda.hpp>
  48. #include <boost/mpl/plus.hpp>
  49. using namespace boost::metaparse;
  50. using int_token = token<int_>;
  51. using sum_op =
  52. boost::mpl::lambda<boost::mpl::plus<boost::mpl::_1, boost::mpl::_2>>::type;
  53. using ints = foldl<int_token, boost::mpl::int_<0>, sum_op>;
  54. static_assert(
  55. get_result<
  56. ints::apply<BOOST_METAPARSE_STRING("11 13 3 21"), start>
  57. >::type::value == 48,
  58. "ints should sum the numbers"
  59. );
  60. static_assert(
  61. get_result<
  62. ints::apply<BOOST_METAPARSE_STRING(""), start>
  63. >::type::value == 0,
  64. "the sum of no elements is 0"
  65. );
  66. [endsect]