Short example of regular expression converted to a state machine?

后端 未结 6 1848
死守一世寂寞
死守一世寂寞 2020-11-29 04:30

In the Stack Overflow podcast #36 (http://blog.stackoverflow.com/2009/01/podcast-36/), this opinion was expressed: Once you understand how easy it is to set up a state machi

6条回答
  •  盖世英雄少女心
    2020-11-29 05:29

    Is the question "How do I choose the states and the transition conditions?", or "How do I implement my abstract state machine in Foo?"

    How do I choose the states and the transition conditions?

    I usually use FSMs for fairly simple problems and choose them intuitively. In my answer to another question about regular expressions, I just looked at the parsing problem as one of being either Inside or outside a tag pair, and wrote out the transitions from there (with a beginning and ending state to keep the implementation clean).

    How do I implement my abstract state machine in Foo?

    If your implementation language supports a structure like c's switch statement, then you switch on the current state and process the input to see which action and/or transition too perform next.

    Without switch-like structures, or if they are deficient in some way, you if style branching. Ugh.

    Written all in one place in c the example I linked would look something like this:

    token_t token;
    state_t state=BEGIN_STATE;
    do {
       switch ( state.getValue() ) {
       case BEGIN_STATE;
          state=OUT_STATE;
          break;
       case OUT_STATE:
          switch ( token.getValue() ) {
             case CODE_TOKEN:
                state = IN_STATE;
                output(token.string());
                break;
             case NEWLINE_TOKEN;
                output("");
                output(token.string());
                break;
             ...
          }
          break;
       ...
       }
    } while (state != END_STATE);
    

    which is pretty messy, so I usually rip the state cases out to separate functions.

提交回复
热议问题