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