Home | Libraries | People | FAQ | More |
Note | |
---|---|
Note that you can find everything that has been included and defined so far here. |
This solution can still be improved. The foldl
summarising the + <number>
elements starts from 0
and
once this is done, we add the value of the first <number>
of the input to it in the first iteration. It would be more straightforward
if foldl
could use the value of the first <number>
as the initial value of the "sum we have so far".
Metaparse provides foldl_start_with_parser
for
this:
> #include <boost/metaparse/foldl_start_with_parser.hpp>
foldl_start_with_parser
is almost the same as foldl
.
The difference is that instead of taking a starting value
for the sum it takes a parser. First it parses the
input with this parser and uses the value it returns as the starting
value. Here is how we can implement our parser using it:
> using exp_parser11 = \ ...> build_parser< \ ...> foldl_start_with_parser< \ ...> sequence<plus_token, int_token>, /* apply this parser repeatedly */ \ ...> int_token, /* use this parser to get the initial value */ \ ...> boost::mpl::quote2<sum_items> /* use this function to add a new value to the summary */ \ ...> > \ ...> >;
This version of exp_parser
uses foldl_start_with_parser
.
This implementation is more compact than the earlier versions. There
is no sequence
element in this: the first <number>
is parsed by int_token
and its value is used as the initial value for the summary. Let's try
it out:
> exp_parser11::apply<BOOST_METAPARSE_STRING("1 + 2 + 3 + 4")>::type mpl_::integral_c<int, 10>
It returns the same result as the earlier version but works differently. Here is a diagram showing how this implementation works: