Design mode-Interpreter mode

Source: Internet
Author: User

Overview:

The future of machine intelligence has become a trend, now the mobile phone can understand English and Mandarin, then my tens of thousands of dialects of the Greater China is also a trend of intelligence, our dialect, although similar to Putonghua, but it is not the same. This may require a new parser to help us.

Our interpreter pattern describes how to define a grammar for a simple language, how to represent a sentence in that language, and how to interpret these sentences.

But explaining a natural language is a complex process, and we explain the interpreter pattern in detail with the addition and subtraction operations as an example.

Class Diagrams and Examples: Abstract Expression Role(abstractexpression): declares an abstract interpretation operation that is implemented for all specific expression roles.

Terminator Expression role (terminalexpression): implements an interpreted operation associated with an element in the grammar, usually with only one terminator expression in an interpreter pattern, but with multiple instances corresponding to different terminator,
Terminator is the basic element used in the language, generally can not be decomposed, such as: X, XA, where A is terminator, because there is no other rule can change a to another symbol, but x can become another symbol, so X is a non-terminator.
non-terminator expression role (nonterminalexpression): Each rule in the grammar corresponds to a non-terminating expression, and non-finalization expressions are incremented according to the complexity of the logic, in principle each grammar rule corresponds to a non-terminator expression.
Environmental Roles (Context): contains some global information outside the interpreter.

Instance:

#include <iostream> #include <map> #include <string> using namespace std;    Class Context {private:map<string, int> valueMap; Public:void AddValue (string key,int value) {valuemap.insert (std::p air<string,int> (Key,va      Lue));      } int GetValue (string key) {return valuemap[key];    }  };  Class Abstractexpression {public:virtual int interpreter (context context) = 0;    };      Class Addnonterminalexpression:public abstractexpression {private:abstractexpression *left;    Abstractexpression *right;  Public:addnonterminalexpression (abstractexpression *left, abstractexpression *right) {this->left =          Left      This->right = right; } int Interpreter (context context) {return This->left->interpreter (context) + this->right-&      Gt;interpreter (context);    }    }; Class Subtractnonterminalexpression: Public Abstractexpression {private:abstractexpression *left;    Abstractexpression *right; Public:subtractnonterminalexpression (abstractexpression *left, abstractexpression *right) {this->l          EFT = left;      This->right = right; } int Interpreter (context context) {return This->left->interpreter (context)-this->right-&      Gt;interpreter (context);    }    };    Class Terminalexpression:public Abstractexpression {private:int i;      public:terminalexpression (int i) {this->i = i;      } int Interpreter (context context) {return this->i;    }  };      int main () {//a-b+c context context;      Context.addvalue ("A", 7);      Context.addvalue ("B", 8);        Context.addvalue ("C", 2); Subtractnonterminalexpression *subtractvalue = new Subtractnonterminalexpression (new Terminalexpression (context. GetValue ("a")), new TerminalexpressioN (Context.getvalue ("B"))); Addnonterminalexpression *addvalue = new Addnonterminalexpression (Subtractvalue, New terminalexpression (context.        GetValue ("C")));        cout<< Addvalue->interpreter (context);    return 0;     }

Applicability:

You might consider using the interpreter mode in the following situations:

(1) A sentence in a language that needs to be interpreted for execution can be represented as an abstract syntax tree.

(2) Some recurring problems can be expressed in a simple language.

(3) The grammar of a language is simpler.

(4) Implementation efficiency is not a critical issue. (Note: Efficient interpreters are not usually implemented by directly interpreting abstract syntax trees, but rather they need to be converted to other forms, and the use of interpreter patterns is not efficient.) )

Pros and Cons: Advantages:

(1) Easy to change and expand grammar. Because the class is used in the interpreter pattern to represent the grammar rules of the language, it is possible to change or extend the grammar through mechanisms such as inheritance.

(2) Each grammar rule can be represented as a class, so it is easy to implement a simple language.

(3) It is easier to implement grammar. Each expression node class in the abstract syntax tree is implemented in a similar way, and the code for these classes is not particularly complex, and the node class code can be generated automatically by some tools.

(4) It is more convenient to add new explanatory expressions. If the user needs to add a new explanatory expression that only needs to add a new terminator expression or non-Terminator expression class, the original expression class code does not need to be modified to conform to the "open and closed principle".

Disadvantages:

(1) difficult to maintain for complex grammars. In interpreter mode, each rule needs to define at least one class, so if a language contains too many grammatical rules, the number of classes will increase dramatically, making the system difficult to manage and maintain, and consider using a parser to replace the interpreter pattern.

(2) less efficient execution. Because of the large number of loops and recursive calls in the interpreter pattern, it is slow to interpret more complex sentences, and the code debugging process is cumbersome.

General:

Try not to use the interpreter mode in important modules because maintenance is difficult. In your project, you can use the scripting language instead of the interpreter pattern.

Original in Csdn.net "http://blog.csdn.net/lcl_data/article/details/9259905"

Design mode-Interpreter mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.