• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1[/==============================================================================
2    Copyright (C) 2001-2015 Joel de Guzman
3    Copyright (C) 2001-2011 Hartmut Kaiser
4
5    Distributed under the Boost Software License, Version 1.0. (See accompanying
6    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7===============================================================================/]
8
9[section Sum - adding numbers]
10
11Here's a parser that sums a comma-separated list of numbers.
12
13Ok we've glossed over some details in our previous examples. First, our
14includes:
15
16    #include <boost/spirit/home/x3.hpp>
17    #include <iostream>
18    #include <string>
19
20Then some using directives:
21
22    namespace x3 = boost::spirit::x3;
23    namespace ascii = boost::spirit::x3::ascii;
24
25    using x3::double_;
26    using ascii::space;
27    using x3::_attr;
28
29Now the actual parser:
30
31    template <typename Iterator>
32    bool adder(Iterator first, Iterator last, double& n)
33    {
34        auto assign = [&](auto& ctx){ n = _attr(ctx); };
35        auto add = [&](auto& ctx){ n += _attr(ctx); };
36
37        bool r = x3::phrase_parse(first, last,
38
39            //  Begin grammar
40            (
41                double_[assign] >> *(',' >> double_[add])
42            )
43            ,
44            //  End grammar
45
46            space);
47
48        if (first != last) // fail if we did not get a full match
49            return false;
50        return r;
51    }
52
53The full cpp file for this example can be found here:
54[@../../../example/x3/sum.cpp sum.cpp]
55
56This is almost like our original numbers list example. We're incrementally
57building on top of our examples. This time though, like in the complex number
58example, we'll be adding the smarts. There's an accumulator (`double& n`) that
59adds the numbers parsed. On a successful parse, this number is the sum of all
60the parsed numbers.
61
62The first `double_` parser attaches this action:
63
64    [&](auto& ctx){ n = _attr(ctx); }
65
66This assigns the parsed result (actually, the attribute of `double_`) to `n`.
67The second `double_` parser attaches this action:
68
69    [&](auto& ctx){ n += _attr(ctx); }
70
71So, subsequent numbers add into `n`.
72
73That wasn't too bad, was it :-) ?
74
75[endsect]
76