The document discusses the Interpreter design pattern. It describes how the Interpreter pattern can be used to define a grammar for a simple language, represent sentences in that language as abstract syntax trees, and interpret those sentences. It provides an example of how to implement an interpreter for a Boolean expression language in Java using the Interpreter pattern. The pattern represents each grammar rule as a class and defines an interpret operation that is recursively called to interpret sentences based on the grammar.
Doppl is a new programming language that aims providing a natural syntax for implementing parallel algorithms, designing data structures for shared memory applications and automated message passing among multiple tasks. The name is an abbreviation of `data oriented parallel programming language`.
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTREjatin batra
Are you searching for C++Training in Ambala Cantt?
Now your search ends here... Batra Computer Centre provides you the best C++ training in Ambala Cantt by the best professionals .
Doppl is a new programming language that aims providing a natural syntax for implementing parallel algorithms, designing data structures for shared memory applications and automated message passing among multiple tasks. The name is an abbreviation of `data oriented parallel programming language`.
C++ Langauage Training in Ambala ! BATRA COMPUTER CENTREjatin batra
Are you searching for C++Training in Ambala Cantt?
Now your search ends here... Batra Computer Centre provides you the best C++ training in Ambala Cantt by the best professionals .
Cross lingual similarity discrimination with translation characteristicsijaia
In cross-lingual plagiarism detection, the similarity between sentences is the basis of judgment. This paper
proposes a discriminative model trained on bilingual corpus to divide a set of sentences in target language
into two classes according their similarities to a given sentence in source language. Positive outputs of the
discriminative model are then ranked according to the similarity probabilities. The translation candidates
of the given sentence are finally selected from the top-n positive results. One of the problems in model
building is the extremely imbalanced training data, in which positive samples are the translations of the
target sentences, while negative samples or the non-translations are numerous or unknown. We train models
on four kinds of sampling sets with same translation characteristics and compare their performances.
Experiments on the open dataset of 1500 pairs of English Chinese sentences are evaluated by three metrics
with satisfying performances, much higher than the baseline system.
Paper Introduction,
"Translating into Morphologically Rich Languages with Synthetic Phrases"
Victor Chahuneau, Eva Schlinger, Noah A. Smith, Chris Dyer (EMNLP2013)
Dear students get fully solved assignments by professionals
Send your semester & Specialization name to our mail id :
stuffstudy5@gmail.com
or
call us at : 098153-33456
C# - Constants and Literals. The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal.
Arabic morphology encapsulates many valuable features such as word’s root. Arabic roots are beingutilized for many tasks; the process of extracting a word’s root is referred to as stemming. Stemming is anessential part of most Natural Language Processing tasks, especially for derivative languages such asArabic. However, stemming is faced with the problem of ambiguity, where two or more roots could beextracted from the same word. On the other hand, distributional semantics is a powerful co-occurrence
model. It captures the meaning of a word based on its context. In this paper, a distributional semantics
model utilizing Smoothed Pointwise Mutual Information (SPMI) is constructed to investigate itseffectiveness on the stemming analysis task. It showed an accuracy of 81.5%, with a at least 9.4%improvement over other stemmers.
International Journal of Engineering Research and Applications (IJERA) is an open access online peer reviewed international journal that publishes research and review articles in the fields of Computer Science, Neural Networks, Electrical Engineering, Software Engineering, Information Technology, Mechanical Engineering, Chemical Engineering, Plastic Engineering, Food Technology, Textile Engineering, Nano Technology & science, Power Electronics, Electronics & Communication Engineering, Computational mathematics, Image processing, Civil Engineering, Structural Engineering, Environmental Engineering, VLSI Testing & Low Power VLSI Design etc.
Top interview questions in c is the extensive list of questions we have created for students.
These questions are helpful for students who are looking for most common asked questions in language c with answers.
Question cover from basic level to advance level
These are theory questions which are also asked in examinations.
Find me on facebook https://www.facebook.com/iwpiww/
Find me on twitter https://twitter.com/seth_avinash
Subscribe me on youtube https://www.youtube.com/c/avinashsethwpnww?sub_confirmation=1
Your learning partner - visionard.com
Abstract A usage of regular expressions to search text is well known and understood as a useful technique. Regular Expressions are generic representations for a string or a collection of strings. Regular expressions (regexps) are one of the most useful tools in computer science. NLP, as an area of computer science, has greatly benefitted from regexps: they are used in phonology, morphology, text analysis, information extraction, & speech recognition. This paper helps a reader to give a general review on usage of regular expressions illustrated with examples from natural language processing. In addition, there is a discussion on different approaches of regular expression in NLP. Keywords— Regular Expression, Natural Language Processing, Tokenization, Longest common subsequence alignment, POS tagging
----------------------------
IJRET : International Journal of Research in Engineering and Technology is an international peer reviewed, online journal published by eSAT Publishing House for the enhancement of research in various disciplines of Engineering and Technology. The aim and scope of the journal is to provide an academic medium and an important reference for the advancement and dissemination of research results that support high-level learning, teaching and research in the fields of Engineering and Technology. We bring together Scientists, Academician, Field Engineers, Scholars and Students of related fields of Engineering and Technology
Quality estimation of machine translation outputs through stemmingijcsa
Machine Translation is the challenging problem for Indian languages. Every day we can see some machine
translators being developed , but getting a high quality automatic translation is still a very distant dream .
The correct translated sentence for Hindi language is rarely found. In this paper, we are emphasizing on
English-Hindi language pair, so in order to preserve the correct MT output we present a ranking system,
which employs some machine learning techniques and morphological features. In ranking no human
intervention is required. We have also validated our results by comparing it with human ranking.
BERT - Part 1 Learning Notes of Senthil KumarSenthil Kumar M
In this part 1 presentation, I have attempted to provide a '30,000 feet view' of BERT (Bidirectional Encoder Representations from Transformer) - a state of the art Language Model in NLP with high level technical explanations. I have attempted to collate useful information about BERT from various useful sources.
Interface in java By Dheeraj Kumar Singhdheeraj_cse
In Java,
An interface is a way through which unrelated objects use to interact with one another.
Using interface, you can specify what a class must do, but not how it does it.
It is not a class but a set of requirements for classes that implement the interface.
PSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATORijistjournal
Pseudocode is an artificial and informal language that helps developers to create algorithms. In this papera software tool is described, for translating the pseudocode into a particular source programminglanguage. This tool compiles the pseudocode given by the user and translates it to a source programminglanguage. The scope of the tool is very much wide as we can extend it to a universal programming toolwhich produces any of the specified programming language from a given pseudocode. Here we present thesolution for translating the pseudocode to a programming language by using the different stages of acompiler
Cross lingual similarity discrimination with translation characteristicsijaia
In cross-lingual plagiarism detection, the similarity between sentences is the basis of judgment. This paper
proposes a discriminative model trained on bilingual corpus to divide a set of sentences in target language
into two classes according their similarities to a given sentence in source language. Positive outputs of the
discriminative model are then ranked according to the similarity probabilities. The translation candidates
of the given sentence are finally selected from the top-n positive results. One of the problems in model
building is the extremely imbalanced training data, in which positive samples are the translations of the
target sentences, while negative samples or the non-translations are numerous or unknown. We train models
on four kinds of sampling sets with same translation characteristics and compare their performances.
Experiments on the open dataset of 1500 pairs of English Chinese sentences are evaluated by three metrics
with satisfying performances, much higher than the baseline system.
Paper Introduction,
"Translating into Morphologically Rich Languages with Synthetic Phrases"
Victor Chahuneau, Eva Schlinger, Noah A. Smith, Chris Dyer (EMNLP2013)
Dear students get fully solved assignments by professionals
Send your semester & Specialization name to our mail id :
stuffstudy5@gmail.com
or
call us at : 098153-33456
C# - Constants and Literals. The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal.
Arabic morphology encapsulates many valuable features such as word’s root. Arabic roots are beingutilized for many tasks; the process of extracting a word’s root is referred to as stemming. Stemming is anessential part of most Natural Language Processing tasks, especially for derivative languages such asArabic. However, stemming is faced with the problem of ambiguity, where two or more roots could beextracted from the same word. On the other hand, distributional semantics is a powerful co-occurrence
model. It captures the meaning of a word based on its context. In this paper, a distributional semantics
model utilizing Smoothed Pointwise Mutual Information (SPMI) is constructed to investigate itseffectiveness on the stemming analysis task. It showed an accuracy of 81.5%, with a at least 9.4%improvement over other stemmers.
International Journal of Engineering Research and Applications (IJERA) is an open access online peer reviewed international journal that publishes research and review articles in the fields of Computer Science, Neural Networks, Electrical Engineering, Software Engineering, Information Technology, Mechanical Engineering, Chemical Engineering, Plastic Engineering, Food Technology, Textile Engineering, Nano Technology & science, Power Electronics, Electronics & Communication Engineering, Computational mathematics, Image processing, Civil Engineering, Structural Engineering, Environmental Engineering, VLSI Testing & Low Power VLSI Design etc.
Top interview questions in c is the extensive list of questions we have created for students.
These questions are helpful for students who are looking for most common asked questions in language c with answers.
Question cover from basic level to advance level
These are theory questions which are also asked in examinations.
Find me on facebook https://www.facebook.com/iwpiww/
Find me on twitter https://twitter.com/seth_avinash
Subscribe me on youtube https://www.youtube.com/c/avinashsethwpnww?sub_confirmation=1
Your learning partner - visionard.com
Abstract A usage of regular expressions to search text is well known and understood as a useful technique. Regular Expressions are generic representations for a string or a collection of strings. Regular expressions (regexps) are one of the most useful tools in computer science. NLP, as an area of computer science, has greatly benefitted from regexps: they are used in phonology, morphology, text analysis, information extraction, & speech recognition. This paper helps a reader to give a general review on usage of regular expressions illustrated with examples from natural language processing. In addition, there is a discussion on different approaches of regular expression in NLP. Keywords— Regular Expression, Natural Language Processing, Tokenization, Longest common subsequence alignment, POS tagging
----------------------------
IJRET : International Journal of Research in Engineering and Technology is an international peer reviewed, online journal published by eSAT Publishing House for the enhancement of research in various disciplines of Engineering and Technology. The aim and scope of the journal is to provide an academic medium and an important reference for the advancement and dissemination of research results that support high-level learning, teaching and research in the fields of Engineering and Technology. We bring together Scientists, Academician, Field Engineers, Scholars and Students of related fields of Engineering and Technology
Quality estimation of machine translation outputs through stemmingijcsa
Machine Translation is the challenging problem for Indian languages. Every day we can see some machine
translators being developed , but getting a high quality automatic translation is still a very distant dream .
The correct translated sentence for Hindi language is rarely found. In this paper, we are emphasizing on
English-Hindi language pair, so in order to preserve the correct MT output we present a ranking system,
which employs some machine learning techniques and morphological features. In ranking no human
intervention is required. We have also validated our results by comparing it with human ranking.
BERT - Part 1 Learning Notes of Senthil KumarSenthil Kumar M
In this part 1 presentation, I have attempted to provide a '30,000 feet view' of BERT (Bidirectional Encoder Representations from Transformer) - a state of the art Language Model in NLP with high level technical explanations. I have attempted to collate useful information about BERT from various useful sources.
Interface in java By Dheeraj Kumar Singhdheeraj_cse
In Java,
An interface is a way through which unrelated objects use to interact with one another.
Using interface, you can specify what a class must do, but not how it does it.
It is not a class but a set of requirements for classes that implement the interface.
PSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATORijistjournal
Pseudocode is an artificial and informal language that helps developers to create algorithms. In this papera software tool is described, for translating the pseudocode into a particular source programminglanguage. This tool compiles the pseudocode given by the user and translates it to a source programminglanguage. The scope of the tool is very much wide as we can extend it to a universal programming toolwhich produces any of the specified programming language from a given pseudocode. Here we present thesolution for translating the pseudocode to a programming language by using the different stages of acompiler
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMURaffi Khatchadourian
Java 8 default methods, which allow interfaces to contain (instance) method implementations, are useful for the skeletal implementation software design pattern. However, it is not easy to transform existing software to exploit default methods. In this talk, I discuss an efficient, fully-automated, type constraint-based refactoring approach that assists developers in taking advantage of enhanced interfaces for their legacy Java software.
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGEIJCI JOURNAL
Pseudocode is an artificial and informal language that helps programmers to develop algorithms. In this
paper a software tool is described, for translating the pseudocode into a particular programming
language. This tool takes the pseudocode as input, compiles it and translates it to a concrete programming
language. The scope of the tool is very much wide as we can extend it to a universal programming tool
which produces any of the specified programming language from a given pseudocode. Here we present the
solution for translating the pseudocode to a programming language by implementing the stages of a
compiler
SOFTWARE TOOL FOR TRANSLATING PSEUDOCODE TO A PROGRAMMING LANGUAGEIJCI JOURNAL
Pseudocode is an artificial and informal language that helps programmers to develop algorithms. In this
paper a software tool is described, for translating the pseudocode into a particular programming
language. This tool takes the pseudocode as input, compiles it and translates it to a concrete programming
language. The scope of the tool is very much wide as we can extend it to a universal programming tool
which produces any of the specified programming language from a given pseudocode. Here we present the
solution for translating the pseudocode to a programming language by implementing the stages of a
compiler.
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
Natural Language Interface for Java Programming: Surveyrahulmonikasharma
It is really difficult for new programmers to deal with the programming language syntax while learning programming .New programmers often struggle because they are forced to learn syntax and general programming skills simultaneously. NaturalJava is a prototype text-based natural language interface for Java programming that accepts English sentences from the keyboard and produces syntactically correct Java source code. This interface mainly contains three components:first is a Sundance which is a partial parser, second is PRISM, A knowledge-based case frame interpreter and third component is Treeface, Abstract Syntax Tree(AST) Manager. This paper aims to provide overview on NaturalJava Prototype which converts english sentences into java source code.
The future of DSLs - functions and formal methodsMarkus Voelter
I have used domain-specific languages to empower non-programmers in healthcare, finance, aerospace, automotive and public administration for years. My approach relies on growing the DSL from a functional programming core, combining the flexibility and power of an algorithmic language with domain-specific constructs that range from temporal data types, state machines and data models to polymorphic dispatch between versions of calculation rules. I rely on the open source MPS workbench to define the languages and their IDE. I am looking to incremental model transformations to desugar domain-specific constructs back to a minimal core language in realtime. That core language will have an interpreter for in-IDE execution and a compiler for deployment. The language will be integrated with formal methods to verify properties of programs, enabling advanced analyses for DSL users. In this talk, I will demo some existing DSLs, provide an illustration of how they are built, and demo prototypes of the future approach while discussing their integration with formal methods.
John Backus identified value-level (object-level) programming languages as programming languages
that combine various values to form other values until the final result values are obtained. Virtually
all our classic programming languages today including C, C++, and Java belong into this category.
Here we identify pattern-level (term-level) programming languages that combine various patterns
to form other patterns until the final result patterns are obtained. New patterns are constructed
from existing ones by the application of pattern-to-pattern functions exploiting pattern matching and
constructors. First-order logic programming languages such as Prolog, OBJ, and Maude belong into
this category. Our insight that pattern-level and value-level programming gives rise to a patternvalue duality is used as the foundation of the design of a new programming language called Asteroid.
Hallmarks of this new programming language design are the developer’s ability to explicitly control
the interpretation or model of expression terms and the notion of ‘patterns as first class citizens’.
In addition to a complete implementation of pattern-level programming Asteroid also supports an
object-oriented style of programming based on prototypes and also subject to pattern matching.
Recruiting in the Digital Age: A Social Media MasterclassLuanWise
In this masterclass, presented at the Global HR Summit on 5th June 2024, Luan Wise explored the essential features of social media platforms that support talent acquisition, including LinkedIn, Facebook, Instagram, X (formerly Twitter) and TikTok.
Affordable Stationery Printing Services in Jaipur | Navpack n PrintNavpack & Print
Looking for professional printing services in Jaipur? Navpack n Print offers high-quality and affordable stationery printing for all your business needs. Stand out with custom stationery designs and fast turnaround times. Contact us today for a quote!
"𝑩𝑬𝑮𝑼𝑵 𝑾𝑰𝑻𝑯 𝑻𝑱 𝑰𝑺 𝑯𝑨𝑳𝑭 𝑫𝑶𝑵𝑬"
𝐓𝐉 𝐂𝐨𝐦𝐬 (𝐓𝐉 𝐂𝐨𝐦𝐦𝐮𝐧𝐢𝐜𝐚𝐭𝐢𝐨𝐧𝐬) is a professional event agency that includes experts in the event-organizing market in Vietnam, Korea, and ASEAN countries. We provide unlimited types of events from Music concerts, Fan meetings, and Culture festivals to Corporate events, Internal company events, Golf tournaments, MICE events, and Exhibitions.
𝐓𝐉 𝐂𝐨𝐦𝐬 provides unlimited package services including such as Event organizing, Event planning, Event production, Manpower, PR marketing, Design 2D/3D, VIP protocols, Interpreter agency, etc.
Sports events - Golf competitions/billiards competitions/company sports events: dynamic and challenging
⭐ 𝐅𝐞𝐚𝐭𝐮𝐫𝐞𝐝 𝐩𝐫𝐨𝐣𝐞𝐜𝐭𝐬:
➢ 2024 BAEKHYUN [Lonsdaleite] IN HO CHI MINH
➢ SUPER JUNIOR-L.S.S. THE SHOW : Th3ee Guys in HO CHI MINH
➢FreenBecky 1st Fan Meeting in Vietnam
➢CHILDREN ART EXHIBITION 2024: BEYOND BARRIERS
➢ WOW K-Music Festival 2023
➢ Winner [CROSS] Tour in HCM
➢ Super Show 9 in HCM with Super Junior
➢ HCMC - Gyeongsangbuk-do Culture and Tourism Festival
➢ Korean Vietnam Partnership - Fair with LG
➢ Korean President visits Samsung Electronics R&D Center
➢ Vietnam Food Expo with Lotte Wellfood
"𝐄𝐯𝐞𝐫𝐲 𝐞𝐯𝐞𝐧𝐭 𝐢𝐬 𝐚 𝐬𝐭𝐨𝐫𝐲, 𝐚 𝐬𝐩𝐞𝐜𝐢𝐚𝐥 𝐣𝐨𝐮𝐫𝐧𝐞𝐲. 𝐖𝐞 𝐚𝐥𝐰𝐚𝐲𝐬 𝐛𝐞𝐥𝐢𝐞𝐯𝐞 𝐭𝐡𝐚𝐭 𝐬𝐡𝐨𝐫𝐭𝐥𝐲 𝐲𝐨𝐮 𝐰𝐢𝐥𝐥 𝐛𝐞 𝐚 𝐩𝐚𝐫𝐭 𝐨𝐟 𝐨𝐮𝐫 𝐬𝐭𝐨𝐫𝐢𝐞𝐬."
Cracking the Workplace Discipline Code Main.pptxWorkforce Group
Cultivating and maintaining discipline within teams is a critical differentiator for successful organisations.
Forward-thinking leaders and business managers understand the impact that discipline has on organisational success. A disciplined workforce operates with clarity, focus, and a shared understanding of expectations, ultimately driving better results, optimising productivity, and facilitating seamless collaboration.
Although discipline is not a one-size-fits-all approach, it can help create a work environment that encourages personal growth and accountability rather than solely relying on punitive measures.
In this deck, you will learn the significance of workplace discipline for organisational success. You’ll also learn
• Four (4) workplace discipline methods you should consider
• The best and most practical approach to implementing workplace discipline.
• Three (3) key tips to maintain a disciplined workplace.
Digital Transformation and IT Strategy Toolkit and TemplatesAurelien Domont, MBA
This Digital Transformation and IT Strategy Toolkit was created by ex-McKinsey, Deloitte and BCG Management Consultants, after more than 5,000 hours of work. It is considered the world's best & most comprehensive Digital Transformation and IT Strategy Toolkit. It includes all the Frameworks, Best Practices & Templates required to successfully undertake the Digital Transformation of your organization and define a robust IT Strategy.
Editable Toolkit to help you reuse our content: 700 Powerpoint slides | 35 Excel sheets | 84 minutes of Video training
This PowerPoint presentation is only a small preview of our Toolkits. For more details, visit www.domontconsulting.com
Personal Brand Statement:
As an Army veteran dedicated to lifelong learning, I bring a disciplined, strategic mindset to my pursuits. I am constantly expanding my knowledge to innovate and lead effectively. My journey is driven by a commitment to excellence, and to make a meaningful impact in the world.
The key differences between the MDR and IVDR in the EUAllensmith572606
In the European Union (EU), two significant regulations have been introduced to enhance the safety and effectiveness of medical devices – the In Vitro Diagnostic Regulation (IVDR) and the Medical Device Regulation (MDR).
https://mavenprofserv.com/comparison-and-highlighting-of-the-key-differences-between-the-mdr-and-ivdr-in-the-eu/
Company Valuation webinar series - Tuesday, 4 June 2024FelixPerez547899
This session provided an update as to the latest valuation data in the UK and then delved into a discussion on the upcoming election and the impacts on valuation. We finished, as always with a Q&A
Putting the SPARK into Virtual Training.pptxCynthia Clay
This 60-minute webinar, sponsored by Adobe, was delivered for the Training Mag Network. It explored the five elements of SPARK: Storytelling, Purpose, Action, Relationships, and Kudos. Knowing how to tell a well-structured story is key to building long-term memory. Stating a clear purpose that doesn't take away from the discovery learning process is critical. Ensuring that people move from theory to practical application is imperative. Creating strong social learning is the key to commitment and engagement. Validating and affirming participants' comments is the way to create a positive learning environment.
Discover the innovative and creative projects that highlight my journey throu...dylandmeas
Discover the innovative and creative projects that highlight my journey through Full Sail University. Below, you’ll find a collection of my work showcasing my skills and expertise in digital marketing, event planning, and media production.
At Techbox Square, in Singapore, we're not just creative web designers and developers, we're the driving force behind your brand identity. Contact us today.
Improving profitability for small businessBen Wann
In this comprehensive presentation, we will explore strategies and practical tips for enhancing profitability in small businesses. Tailored to meet the unique challenges faced by small enterprises, this session covers various aspects that directly impact the bottom line. Attendees will learn how to optimize operational efficiency, manage expenses, and increase revenue through innovative marketing and customer engagement techniques.
2. Amirkabir University of Technology Computer Engineering Department Fall 2010
Intent
Given a language, define a representation for its grammar along
with an interpreter that uses the representation to interpret
sentences in the language.
2
3. Amirkabir University of Technology Computer Engineering Department Fall 2010
Motivation
The Interpreter pattern describes:
how to define a grammar for simple languages,
represent sentences in the language,
and interpret these sentences.
3
4. Amirkabir University of Technology Computer Engineering Department Fall 2010
4
Basically the Interpreter pattern has limited area where it can be
applied. We can discuss the Interpreter pattern only in terms of
formal grammars but in this area there are better solutions that
is why it is not frequently used.
The Interpreter pattern uses a class to represent each grammar
rule.
5. Amirkabir University of Technology Computer Engineering Department Fall 2010
Applicability
Use the Interpreter pattern when there is a language to interpret,
and you can represent statements in the language as abstract
syntax trees.
The Interpreter pattern works best when
1) the grammar is simple.
2) For complex grammars, the class hierarchy for the grammar becomes large
and unmanageable.
3) They can interpret expressions without building abstract syntax trees,
which can save space and possibly time.
5
6. Amirkabir University of Technology Computer Engineering Department Fall 2010
Applicability (cont…)
– efficiency is not a critical concern.
2) The most efficient interpreters are usually not implemented by
interpreting parse trees directly but by first translating them into another
form.
6
9. Amirkabir University of Technology Computer Engineering Department Fall 2010
Participants
AbstractExpression
declares an abstract Interpret operation that is common to all nodes in the
abstract syntax tree.
TerminalExpression
implements an Interpret operation associated with terminal symbols in the
grammar.
an instance is required for every terminal symbol in a sentence.
NonterminalExpression
one such class is required for every rule R ::= R1 R2 ... Rn in the grammar.
maintains instance variables of type AbstractExpression for each of the
symbols R1 through Rn.
9
10. Amirkabir University of Technology Computer Engineering Department Fall 2010
Participants (cont…)
implements an Interpret operation for nonterminal symbols in the
grammar. Interpret typically calls itself recursively on the variables
representing R1 through Rn.
Context
contains information that's global to the interpreter.
Client
builds (or is given) an abstract syntax tree representing a particular
sentence in the language that the grammar defines.
invokes the Interpret operation.
10
11. Amirkabir University of Technology Computer Engineering Department Fall 2010
Collaborations
The client builds (or is given) the sentence as an abstract syntax
tree of NonterminalExpression and TerminalExpression instances.
Then the client initializes the context and invokes the Interpret
operation.
Each NonterminalExpression node defines Interpret in terms of
Interpret on each subexpression. The Interpret operation of each
TerminalExpression defines the base case in the recursion.
The Interpret operations at each node use the context to store and
access the state of the interpreter.
11
12. Amirkabir University of Technology Computer Engineering Department Fall 2010
Consequences
Benefits:
It's easy to change and extend the grammar. Because the pattern uses classes to
represent grammar rules, you can use inheritance to change or extend the
grammar.
Implementing the grammar is easy, too. Classes defining nodes in the abstract
syntax tree have similar implementations.
Adding new ways to interpret expressions. The Interpreter pattern makes it easier
to evaluate an expression in a new way.
For example, you can support pretty printing or type-checking an expression by defining a
new operation on the expression classes.
If you keep creating new ways of interpreting an expression, then consider using the Visitor
pattern to avoid changing the grammar classes.
12
13. Amirkabir University of Technology Computer Engineering Department Fall 2010
Consequences (cont…)
Liability:
Complex grammars are hard to maintain. The Interpreter pattern
defines at least one class for every rule in the grammar. Hence
grammars containing many rules can be hard to manage and
maintain. when the grammar is very complex, other techniques such
as parser or compiler generators are more appropriate.
13
14. Amirkabir University of Technology Computer Engineering Department Fall 2010
Implementation
1) Creating the abstract syntax tree.
The Interpreter pattern doesn't explain how to create an abstract syntax tree.
The abstract syntax tree can be created by a table-driven parser, by a hand-
crafted parser, or directly by the client.
2) Defining the Interpret operation.
If it's common to create a new interpreter, then it's better to use the Visitor
pattern to put Interpret in a separate "visitor" object.
3) Sharing terminal symbols with the Flyweight pattern.
Grammars whose sentences contain many occurrences of a terminal symbol
might benefit from sharing a single copy of that symbol.
14
15. Amirkabir University of Technology Computer Engineering Department Fall 2010
Example
First example is a system for manipulating and evaluating Boolean
expressions implemented in C++. The grammar is defined as follows:
We define two operations on Boolean expressions:
1. Evaluate, evaluates a Boolean expression in a context that assigns a true or false
value to each variable.
2. Replace, produces a new Boolean expression by replacing a variable with an
expression.
15
17. Amirkabir University of Technology Computer Engineering Department Fall 2010
17
Create an expression interface:
- Expression.java
public interface Expression
{
public boolean interpret(String context);
}
18. Amirkabir University of Technology Computer Engineering Department Fall 2010
18
Create concrete classes implementing the above interface:
- TerminalExpression.java
public class TerminalExpression implements Expression
{
private String data;
public TerminalExpression(String data){
this.data = data; }
@Override public boolean interpret(String context)
{ if(context.contains(data)){ return true;
} return false;
} }
19. Amirkabir University of Technology Computer Engineering Department Fall 2010
19
- OrExpression.java
public class OrExpression implements Expression {
private Expression expr1 = null;
private Expression expr2 = null;
public OrExpression(Expression expr1, Expression expr2)
{
this.expr1 = expr1;
this.expr2 = expr2;
}
@Override
public boolean interpret(String context) {
return expr1.interpret(context) || expr2.interpret(context);
} }
20. Amirkabir University of Technology Computer Engineering Department Fall 2010
20
- AndExpression.java
public class AndExpression implements Expression
{
private Expression expr1 = null;
private Expression expr2 = null;
public AndExpression(Expression expr1, Expression expr2)
{
this.expr1 = expr1;
this.expr2 = expr2; }
@Override
public boolean interpret(String context) {
return expr1.interpret(context) && expr2.interpret(context);
} }
21. Amirkabir University of Technology Computer Engineering Department Fall 2010
21
nterpreterPatternDemo.java
public class InterpreterPatternDemo { //Rule: Robert and John are
male public static Expression getMaleExpression(){ Expression
robert = new TerminalExpression("Robert"); Expression john = new
TerminalExpression("John"); return new OrExpression(robert, john);
} //Rule: Julie is a married women public static Expression
getMarriedWomanExpression(){ Expression julie = new
TerminalExpression("Julie"); Expression married = new
TerminalExpression("Married"); return new AndExpression(julie,
married); }
22. Amirkabir University of Technology Computer Engineering Department Fall 2010
22
public static void main(String[] args)
{
Expression isMale = getMaleExpression();
Expression isMarriedWoman = getMarriedWomanExpression();
System.out.println("John is male? " +
isMale.interpret("John"));
System.out.println("Julie is a married women? " +
isMarriedWoman.interpret("Married Julie"));
} }
23. Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
Replace shows how the Interpreter pattern can be used for more
than just evaluating expressions. In this case, it manipulates the
expression itself.
23
24. Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
BooleanExp defines the interface for all classes that define a
Boolean expression:
public abstract class BooleanExp
{
public BooleanExp(){}
public abstract bool Evaluate(Context aContext);
public abstract BooleanExp Replace(string name, BooleanExp bExp);
public abstract BooleanExp Copy();
}
24
25. Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
The class Context defines a mapping from variables to Boolean values.
public class Context
{
Hashtable values;
public Context()
{
values = new Hashtable();
}
public bool Lookup(VariableExp varExp)
{
return(bool)values[varExp.name];
}
public void Assign(VariableExp varExp, bool bval)
{
values.Add(varExp.name, bval);
}
}
25
26. Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
public class VariableExp : BooleanExp
{
public string name;
public VariableExp(string _name){name = _name;}
public override bool Evaluate(Context aContext)
{
return aContext.Lookup(this);
}
public override BooleanExp Replace(string _name, BooleanExp bExp)
{
if (_name.Equals(name))
return bExp.Copy();
else
return new VariableExp(name);
}
public override BooleanExp Copy()
{
return new VariableExp(name);
}
}
26
27. Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
public class AndExp : BooleanExp
{
public BooleanExp operand1;
public BooleanExp operand2;
public VariableExp(BooleanExp op1, BooleanExp op2)
{operand1 = op1; operand2 = op2;}
public override bool Evaluate(Context aContext)
{
return operand1.Evaluate(aContext) &&
operand2.Evaluate(aContext);
}
public override BooleanExp Replace(string _name, BooleanExp bExp)
{
return new AndExp(operand1.Replace(_name, bExp),
operand2.Replace(_name, bExp));
}
public override BooleanExp Copy()
{
return new AndExp(operand1.Copy(),operand2.Copy());
}
}
27
28. Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
(true and x) or (y and (not x))
BooleanExp expression;
Context context;
VariableExp x = new VariableExp("X");
VariableExp y = new VariableExp("Y");
expression = new OrExp( new AndExp(new Constant(true), x), new AndExp(y, new
NotExp(x)) );
context.Assign(x, false);
context.Assign(y, true);
bool result = expression.Evaluate(context);
we can replace the variable y with a new expression and then reevaluate it:
VariableExp z = new VariableExp("Z");
NotExp not_z = new NotExp(z);
BooleanExp replacement = expression.Replace("Y", not_z);
context.Assign(z, true);
result = replacement.Evaluate(context);
28
29. Amirkabir University of Technology Computer Engineering Department Fall 2010
Example (cont…)
This example illustrates an important point about the Interpreter
pattern: many kinds of operations can "interpret" a sentence.
Evaluate fits our idea of what an interpreter should do most closely—
that is, it interprets a program or expression and returns a simple
result.
However, Replace can be viewed as an interpreter as well. It's an
interpreter whose context is the name of the variable being replaced
along with the expression that replaces it, and whose result is a new
expression.
Even Copy can be thought of as an interpreter with an empty context.
29
30. Amirkabir University of Technology Computer Engineering Department Fall 2010
Related Patterns
Composite : The abstract syntax tree is an instance of the Composite
pattern.
Flyweight shows how to share terminal symbols within the abstract
syntax tree.
Iterator : The interpreter can use an Iterator to traverse the structure.
Visitor can be used to maintain the behavior in each node in the abstract
syntax tree in one class.
30