Boost logo

Boost Users :

From: Joel de Guzman (djowel_at_[hidden])
Date: 2003-06-24 07:45:11


---- Original Message ----
From: "joshwaxman" <JoshWaxman_at_[hidden]>

You might want to post Spirit related questions to:

Spirit-general mailing list
Spirit-general_at_[hidden]
https://lists.sourceforge.net/lists/listinfo/spirit-general

Anyway... try this:

#define BOOST_SPIRIT_DEBUG
#include <iostream>
#include <boost/spirit/core.hpp>
using namespace boost::spirit;
using namespace std;

int
main()
{
    rule <> S; // a palindrome of 'a' and 'b' chars

    S =
        ('a' >> S >> 'a')
    | ('b' >> S >> 'b')
    | 'a'
    | 'b'
    | eps_p
    ;

    char * str = "aabaa";
    cout << parse(str, S).full;
    BOOST_SPIRIT_DEBUG_RULE(S);
    return 0;
}

Some notes:

1) use the built in Spirit debugger to see what's happening and to
    better diagnose the problem.

2) Your grammar is inherently ambiguous. Some alternatives start
    with the same 'a' or 'b'. In such cases, use Spirit's short circuiting
    feature to disambiguate the grammar (i.e. move more specialized
    rules higher to give it more precedence).

3) You might be interested to see a more general palindrome parser.
    ( Actually this grammar is prevalent, think about XML/HTML
    tag processing for instance: <tag1><tag2></tag2></tag1> ).
    Check out: /spirit/libs/spirit/test/closure_tests.cpp

HTH,

-- 
Joel de Guzman
joel at boost-consulting.com
http://www.boost-consulting.com
http://spirit.sf.net
| | Hi.
| | I just started playing with spirit and tried the
| | following code to 
| | match palindromes of strings consisting of a's and b's.
| | Why won't 
| | this work? (It prints 0, not 1)
| | 
| | #include "boost/spirit/core.hpp"
| | #include <iostream.h>
| | 
| | using namespace boost::spirit;
| | 
| | int main(int argc, char* argv[])
| | {
| | rule <> S;
| | S = ch_p('a')
| | | ch_p('b')
| | | epsilon_p
| | | ('a' >> S >> 'a')
| | | ('b' >> S >> 'b');
| | 
| | 
| | 
| | char * str = "aabaa";
| | cout << parse(str, S).full;
| | 
| | 
| | return 0;
| | }

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net