Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Automata-based programming

From Wikipedia, the free encyclopedia
Programming paradigm based on formal automatons
For other uses, seeAutomata-based programming (Shalyto's approach).

Automata-based programming is aprogramming paradigm in which the program or part of it is thought of as a model of afinite-state machine (FSM) or any other (often more complicated) formal automaton (seeautomata theory). Sometimes a potentially infinite set of possible states is introduced, and such a set can have a complicated structure, not just an enumeration.

Finite-state machine-based programming is generally the same, but, formally speaking, does not cover all possible variants, as FSM stands for finite-state machine, and automata-based programming does not necessarily employ FSMs in the strict sense.

The following properties are key indicators for automata-based programming:

  • The time period of the program's execution is clearly separated down to theautomaton steps. Each step is effectively an execution of a code section (same for all the steps) which has a single entry point. That section might be divided down to subsections to be executed depending on different states, although this is not necessary.
  • Any communication between the automaton steps is only possible via the explicitly noted set of variables named theautomaton state. Between any two steps, the program cannot have implicit components of its state, such as local variables' values, return addresses, the current instruction pointer, etc. That is, the state of the whole program, taken at any two moments of entering an automaton step, can only differ in the values of the variables being considered as the automaton state.

The whole execution of the automata-based code is acycle of the automaton steps.

Another reason for using the notion of automata-based programming is that the programmer's style of thinking about the program in this technique is very similar to the style of thinking used to solve mathematical tasks usingTuring machines,Markov algorithms, etc.

Example

[edit]

Task

[edit]

Consider the task of reading a text fromstandard input line-by-line and writing the first word of each line tostandard output. First we skip all leadingwhitespace characters, if any. Then we print all the characters of the first word. Finally we skip all the trailing characters until anewline character is encountered. Whenever a sequence of newline characters is encountered not at the beginning of the stream, we print only the first one and skip the remaining ones; else, we skip all. Next we restart the process at the following line. Upon encountering theend-of-file condition (regardless of the stage), we stop.

Traditional program

[edit]

A traditional program inC which performs the above task could look like this:

#include<ctype.h>#include<stdio.h>intmain(void){intc;do{do{c=getchar();}while(isspace(c));while(!isspace(c)&&c!=EOF){putchar(c);c=getchar();}while(c!='\n'&&c!=EOF){c=getchar();}if(c=='\n'){putchar(c);}}while(c!=EOF);return0;}

For instance, compiling and running the above program on this input:

$clangprogram.c&&(printf"\t\v\f\r \n\n\t\v\f\r foo bar baz\n\n\t\v\f\r qux quux corge"|./a.out)

yields:

fooqux

Automata-based program

[edit]

Procedural

[edit]

The same task can be solved by thinking in terms offinite-state machines. The parsing of a line has three stages: skipping the leading whitespace characters, printing the characters of the first word and skipping the trailing characters. These states are calledBEFORE,INSIDE andAFTER. An automata-based version of the program could look like this:

#include<ctype.h>#include<stdio.h>enumState{BEFORE,INSIDE,AFTER};intmain(void){intc;enumStates=BEFORE;while((c=getchar())!=EOF){switch(s){caseBEFORE:if(!isspace(c)){putchar(c);s=INSIDE;}break;caseINSIDE:if(c=='\n'){putchar(c);s=BEFORE;}elseif(isspace(c)){s=AFTER;}else{putchar(c);}break;caseAFTER:if(c=='\n'){putchar(c);s=BEFORE;}break;}}return0;}

Although the program now looks longer, it has at least one significant advantage: there is onlyone reading (that is, call to thegetchar function) instruction. Besides that, there is only one loop instead of the four the traditional version had. The body of thewhile loop is theautomaton step and the loop itself is thecycle of the automaton step. The program implements the work of a finite-state machine shown in the state diagram.

The most important property of the program is that the automaton step code section is clearly localized. With an explicit functionstep for the automation step, the program better demonstrates this property:

#include<ctype.h>#include<stdio.h>enumState{BEFORE,INSIDE,AFTER};voidstep(enumState*consts,intconstc){switch(*s){caseBEFORE:if(!isspace(c)){putchar(c);*s=INSIDE;}break;caseINSIDE:if(c=='\n'){putchar(c);*s=BEFORE;}elseif(isspace(c)){*s=AFTER;}else{putchar(c);}break;caseAFTER:if(c=='\n'){putchar(c);*s=BEFORE;}break;}}intmain(void){intc;enumStates=BEFORE;while((c=getchar())!=EOF){step(&s,c);}return0;}

The program now clearly demonstrates the basic properties of automata-based code:

  • Time periods of automaton step executions may not overlap;
  • The only information passed from the previous step to the next is the explicitly specifiedautomaton state.

A finite automaton can be defined by astate-transition table whose rows stand for the current states, columns stand for the inputs, and cells stand for the next states and actions to perform.

State-transition table
Input
Current state
newlinewhitespaceother
beforebeforebeforeinside/print
insidebefore/printafterinside/print
afterbefore/printafterafter
State diagram
Thestate diagram of a finite-state machine that prints the first word of each line of an input stream. The machine follows exactly one transition on each step, depending on the current state and the encountered character. The action accompanying a transition is either a no-operation or the printing of the encountered character, denoted withprint.

Generally speaking, an automata-based program can naturally use this approach. With an explicit two-dimensional arraytransitions for the state-transition table, the program uses this approach:

#include<ctype.h>#include<stdio.h>enumState{BEFORE,INSIDE,AFTER};voidnop(intconstc){}voidprint(intconstc){putchar(c);}structBranch{enumStateconstnext_state;void(*action)(int);};structBranchconsttransitions[3][3]={//   newline         whitespace         other             Inputs/States{{BEFORE,&nop},{BEFORE,&nop},{INSIDE,&print}},// before{{BEFORE,&print},{AFTER,&nop},{INSIDE,&print}},// inside{{BEFORE,&print},{AFTER,&nop},{AFTER,&nop}}// after};voidstep(enumState*consts,intconstc){intconstrow=(*s==BEFORE)?0:(*s==INSIDE)?1:2;intconstcolumn=(c=='\n')?0:isspace(c)?1:2;structBranchconst*constb=&transitions[row][column];*s=b->next_state;b->action(c);}intmain(void){intc;enumStates=BEFORE;while((c=getchar())!=EOF){step(&s,c);}return0;}

Object-oriented

[edit]

If the implementation language supportsobject-oriented programming, a simple refactoring of the program is toencapsulate the automaton into an object, thus hiding its implementation details. The program inC++ using object-oriented style could look like this:

#include<ctype.h>#include<stdio.h>enumState{BEFORE,INSIDE,AFTER};structBranch{enumStateconstnext_state;void(*action)(int);};classStateMachine{public:StateMachine();voidfeedChar(int);protected:staticvoidnop(int);staticvoidprint(int);private:enumState_state;staticstructBranchconst_transitions[3][3];};StateMachine::StateMachine():_state(BEFORE){}voidStateMachine::feedChar(intconstc){intconstrow=(_state==BEFORE)?0:(_state==INSIDE)?1:2;intconstcolumn=(c=='\n')?0:isspace(c)?1:2;structBranchconst*constb=&_transitions[row][column];_state=b->next_state;b->action(c);}voidStateMachine::nop(intconstc){}voidStateMachine::print(intconstc){putchar(c);}structBranchconstStateMachine::_transitions[3][3]={//   newline         whitespace         other             Inputs/States{{BEFORE,&nop},{BEFORE,&nop},{INSIDE,&print}},// before{{BEFORE,&print},{AFTER,&nop},{INSIDE,&print}},// inside{{BEFORE,&print},{AFTER,&nop},{AFTER,&nop}}// after};intmain(){intc;StateMachinem;while((c=getchar())!=EOF){m.feedChar(c);}return0;}

To minimize changes not directly related to the subject of the article, theinput/outputgetchar andputchar functions from the standard library ofC are being used.

Thestate design pattern is a way for an object to change its behavior at runtime according to its internal statewithout resorting to large conditional statements or table lookups thanks to virtual function calls. Its main advantage over code using large conditional statements is that state-specific code is distributed across different objects rather than localized in a monolithic block, which improves maintainability. Its main advantages over code using state-transition tables are that virtual function calls are often more efficient than table lookups, that state-transition criteria are more explicit than in tabular format, and that it is easier to add actions accompanying state transitions. However it introduces a new problem: the number of classes makes the code less compact than the other approaches. The program using the state design pattern could look like this:

#include<ctype.h>#include<stdio.h>classStateMachine;classState{public:virtualvoidfeedChar(StateMachine*,int)const=0;};classBefore:publicState{public:staticStateconst*instantiate();virtualvoidfeedChar(StateMachine*,int)constoverride;protected:Before()=default;private:staticStateconst*_instance;};classInside:publicState{public:staticStateconst*instantiate();virtualvoidfeedChar(StateMachine*,int)constoverride;protected:Inside()=default;private:staticStateconst*_instance;};classAfter:publicState{public:staticStateconst*instantiate();virtualvoidfeedChar(StateMachine*,int)constoverride;protected:After()=default;private:staticStateconst*_instance;};classStateMachine{public:StateMachine();voidfeedChar(int);protected:voidsetState(Stateconst*);private:Stateconst*_state;friendclassBefore;friendclassInside;friendclassAfter;};Stateconst*Before::instantiate(){if(!_instance){_instance=newBefore;}return_instance;}voidBefore::feedChar(StateMachine*constm,intconstc)const{if(!isspace(c)){putchar(c);m->setState(Inside::instantiate());}}Stateconst*Before::_instance=nullptr;Stateconst*Inside::instantiate(){if(!_instance){_instance=newInside;}return_instance;}voidInside::feedChar(StateMachine*constm,intconstc)const{if(c=='\n'){putchar(c);m->setState(Before::instantiate());}elseif(isspace(c)){m->setState(After::instantiate());}else{putchar(c);}}Stateconst*Inside::_instance=nullptr;Stateconst*After::instantiate(){if(!_instance){_instance=newAfter;}return_instance;}voidAfter::feedChar(StateMachine*constm,intconstc)const{if(c=='\n'){putchar(c);m->setState(Before::instantiate());}}Stateconst*After::_instance=nullptr;StateMachine::StateMachine():_state(Before::instantiate()){}voidStateMachine::feedChar(intconstc){_state->feedChar(this,c);}voidStateMachine::setState(Stateconst*consts){_state=s;}intmain(){intc;StateMachinem;while((c=getchar())!=EOF){m.feedChar(c);}return0;}

Automation and automata

[edit]

Automata-based programming indeed closely matches the programming needs found in the field ofautomation.

A production cycle is commonly modelled as:

  • a sequence of stages stepping according to input data (from captors);
  • a set of actions performed depending on the current stage.

Various dedicated programming languages allow expressing such a model in more or less sophisticated ways.

Automation program

[edit]

The example presented above could be expressed according to this view like in the followingpseudo-code ('set' activates a logic variable, 'reset' inactivates a logic variable, ':' assigns a variable, and '=' tests for equality):

newline: '\n'whitespace: ('\t', '\n', '\v', '\f', '\r', ' ')states: (before, inside, after)setState(c) {  if before and (c != newline and c not in whitespace) then set inside  if inside then (if c in whitespace then set after else if c = newline then set before)  if after and c = newline then set before}doAction(c) {  if before and (c != newline and c not in whitespace) then write(c)  if inside and c not in whitespace then write(c)  if after and c = newline then write(c)}cycle {  set before  loop until (c: readCharacter) = EOL {    setState(c)    doAction(c)  }}

The separation of routines expressing cycle progression on one side, and actual action on the other (matching input and output) allows clearer and simpler code.

Events

[edit]

In the field of automation, stepping from step to step depends on input data coming from the machine itself. This is represented in the program by reading characters from a text. In reality, those data inform about position, speed, temperature, etc. of critical elements of a machine.

Like inGUI programming,changes in the machine state can thus be considered as events causing the passage from a state to another, until the final one is reached. The combination of possible states can generate a wide variety of events, thus defining a more complex production cycle. As a consequence, cycles are usually far to be simple linear sequences. There are commonly parallel branches running together and alternatives selected according to different events, schematically represented below:

   s:stage   c:condition      s1   |   |-c2   |   s2   |   ----------   |        |   |-c31    |-c32   |        |  s31       s32   |        |   |-c41    |-c42   |        |   ----------   |   s4

Applications

[edit]

Automata-based programming is widely used inlexical andsyntactic analyses.[1]

Besides that, thinking in terms of automata (that is, breaking the execution process down toautomaton steps and passing information from step to step through the explicitautomaton state) is necessary forevent-driven programming as the only alternative to using parallel processes or threads.

The notions of states and state machines are often used in the field offormal specification. For instance,UML-based software architecture development usesstate diagrams to specify the behaviour of the program. Also variouscommunication protocols are often specified using the explicit notion of state (e.g.,RFC 793).

Thinking in terms of automata (steps and states) can also be used to describe semantics of someprogramming languages. For example, the execution of a program written in theRefal language is described as a sequence ofsteps of a so-called abstract Refal machine; the state of the machine is aview (an arbitrary Refal expression without variables).

Continuations in theScheme language require thinking in terms of steps and states, although Scheme itself is in no way automata-related (it is recursive). To make it possible for thecall/cc feature to work, implementation needs to be able to catch a whole state of the executing program, which is only possible when there is no implicit part in the state. Such a caught state is the very thing calledcontinuation, and it can be considered as the state of a (relatively complicated) automaton. The automaton step is deducing the next continuation from the previous one, and the execution process is the cycle of such steps.

Alexander Ollongren in his book[2] explains the so-calledVienna method of programming languages semantics description which is fully based on formal automata.

The STAT system[1] is a good example of using the automata-based approach; this system, besides other features, includes an embedded language calledSTATL which is purely automata-oriented.

History

[edit]

Automata-based techniques were used widely in the domains where there are algorithms based on automata theory, such as formal language analyses.[1]

One of the early papers on this is by Johnson et al., 1968.[3]

One of the earliest mentions of automata-based programming as a general technique is found in the paper byPeter Naur, 1963.[4] The author calls the techniqueTuring machine approach, however no realTuring machine is given in the paper; instead, the technique based on steps and states is described.

Comparison with imperative and procedural programming

[edit]

The notion ofstate is not exclusive property of automata-based programming.[5]Generally speaking, state (orprogram state) appears during execution of anycomputer program, as a combination of all information that can change during the execution. For instance, a state of a traditionalimperative program consists of

  • values of all variables and the information stored within dynamic memory;
  • values stored in registers;
  • stack contents (includinglocal variables' values and return addresses);
  • current value of theinstruction pointer.

These can be divided to theexplicit part (such as values stored in variables) and theimplicit part (return addresses and the instruction pointer).

Having said this, an automata-based program can be considered as a special case of an imperative program, in which implicit part of the state is minimized. The state of the whole program taken at the two distinct moments of entering thestep code section can differ in the automaton state only. This simplifies the analysis of the program.

Object-oriented programming relationship

[edit]

In the theory ofobject-oriented programming, anobject is said to have an internalstate and is capable ofreceiving messages,responding to them,sending messages to other objects and changing its internal state during message handling. In more practical terminology,to call an object's method is considered the same asto send a message to the object.

Thus, on the one hand, objects from object-oriented programming can be considered as automata (or models of automata) whosestate is the combination of private fields, and one or more methods are considered to be thestep. Such methods must not call each other nor themselves, neither directly nor indirectly, otherwise the object can not be considered to be implemented in an automata-based manner.

On the other hand, object is good for implementing a model of an automaton. When the automata-based approach is used within an object-oriented language, an automaton model is usually implemented by a class, the state is represented with private fields of the class, and the step is implemented as a method; such a method is usually the only non-constant public method of the class (besides constructors and destructors). Other public methods could query the state but do not change it. All the secondary methods (such as particular state handlers) are usually hidden within the private part of the class.

See also

[edit]

References

[edit]
  1. ^abAho, Alfred V.; Ullman, Jeffrey D. (1973).The theory of parsing, translation and compiling. Vol. 1. Englewood Cliffs, N. J.: Prentice-Hall.ISBN 0-13-914564-8.
  2. ^Ollongren, Alexander (1974).Definition of programming languages by interpreting automata. London: Academic Press.ISBN 0-12-525750-3.
  3. ^Johnson, W. L.; Porter, J. H.; Ackley, S. I.; Ross, D. T. (1968)."Automatic generation of efficient lexical processors using finite state techniques".Comm ACM.11 (12):805–813.doi:10.1145/364175.364185.S2CID 17253809.
  4. ^Naur, Peter (September 1963). "The design of the GIER ALGOL compiler Part II".BIT Numerical Mathematics.3 (3):145–166.doi:10.1007/BF01939983.S2CID 189785656.
  5. ^"Automata-based programming"(PDF).Scientific and Technical Journal of Information Technologies, Mechanics and Optics (53). 2008.

External links

[edit]
Imperative
Structured
Object-oriented
(comparison,list)
Declarative
Functional
(comparison)
Dataflow
Logic
Domain-
specific
language

(DSL)
Concurrent,
distributed,
parallel
Metaprogramming
Separation
of concerns
Retrieved from "https://en.wikipedia.org/w/index.php?title=Automata-based_programming&oldid=1282644115"
Category:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp