Page | 1
Overview of an Expert System:
An expert system is a set of programs that manipulate encoded knowledge to solve
problems in a specialized domain that normally requires human expertise. An expert
system’s knowledge is obtained from expert sources and coded in a form suitable for the
system to use in its inference or reasoning processes. The expert knowledge must be
obtained from specialists or other sources of expertise such as texts, journals, articles
An expert system is software that attempts to provide an answer to a problem,
or clarify uncertainties where normally one or more human experts would need to be
consulted. Expert systems are most common in a specific problem domain, and are a
traditional application and/or subfield of artificial intelligence. A wide variety of
methods can be used to simulate the performance of the expert however common to
most or all are 1) the creation of a so-called "knowledgebase" which uses some
knowledge representation formalism to capture the Subject Matter Expert's (SME)
knowledge and 2) a process of gathering that knowledge from the SME and codifying it
according to the formalism, which is called knowledge engineering. Expert systems may
or may not have learning components but a third common element is that once the
system is developed it is proven by being placed in the same real world problem solving
situation as the human SME, typically as an aid to human workers or a supplement to
some information system.
Page | 2
Characteristic features of Expert Systems:
Expert Systems use knowledge rather than data to control the solution process.
The knowledge is encoded and maintained as an entity separate from the control
program. It is not compiled together with the control program itself. This permits
the incremental addition and modification of the knowledge base without
recompilation of the control programs.
Expert systems are capable of explaining how a particular conclusion was reached.
Expert systems use symbolic representations for knowledge and perform their
inference through symbolic computations.
Expert systems often reason with Meta knowledge.
Expert System Architecture:
Figure shows the most important modules that make up a rule-based expert system. The
user interacts with the system through a user interface which may use menus, natural
language or any other style of interaction). Then an inference engine is used to reason
with both the expert knowledge (extracted from our friendly expert) and data specific to
the particular problem being solved. The expert knowledge will typically be in the form
of a set of IF-THEN rules. The case specific data includes both data provided by the user
and partial conclusions (along with certainty measures) based on this data. In a simple
forward chaining rule-based system the case specific data will be the elements in
Page | 3
Almost all expert systems also have an explanation subsystem, which allows the program
to explain its reasoning to the user. Some systems also have a knowledge base editor
which helps the expert or knowledge engineer to easily update and check the knowledge
One important feature of expert systems is the way they (usually) separate domain
specific knowledge from more general purpose reasoning and representation
techniques. The general purpose bit (in the dotted box in the figure) is referred to as an
expert system shell. As we see in the figure, the shell will provide the inference engine
(and knowledge representation scheme), a user interface, an explanation system and
sometimes a knowledge base editor. Given a new kind of problem to solve (say, car
design), we can usually find a shell that provides the right sort of support for that
problem, so all we need to do is provide the expert knowledge. There are numerous
commercial expert system shells, each one appropriate for a slightly different range of
problems. (Expert systems work in industry includes both writing expert system shells
and writing expert systems using shells.) Using shells to write expert systems generally
Page | 4
greatly reduces the cost and time of development (compared with writing the expert
system from scratch).
Example of Expert System:
MYCIN was an early expert system developed over five or six years in the early 1970s at
Stanford University. It was written in Lisp as the doctoral dissertation of Edward
Shortliffe under the direction of Bruce Buchanan, Stanley N. Cohen and others. It arose in
the laboratory that had created the earlier Dendral expert system, but emphasized the
use of judgmental rules that had elements of uncertainty (known as certainty factors)
associated with them. This expert system was designed to identify bacteria causing
severe infections, such as bacteremia and meningitis, and to recommend antibiotics,
with the dosage adjusted for patient's body weight — the name derived from the
antibiotics themselves, as many antibiotics have the suffix "-mycin". The Mycin system
was also used for the diagnosis of blood clotting diseases.
Applications of Expert System:
The spectrum of applications of expert systems technology to industrial and commercial
problems is so wide as to defy easy characterization. The applications find their way into
most areas of knowledge work. They are as varied as helping salespersons sell modular
factory-built homes to helping NASA plan the maintenance of a space shuttle in
preparation for its next flight.
Applications tend to cluster into seven major classes.
Page | 5
Diagnosis and Troubleshooting of Devices and Systems of All Kinds:
This class comprises systems that deduce faults and suggest corrective actions for a
malfunctioning device or process. Medical diagnosis was one of the first knowledge areas
to which ES technology was applied (for example, see Shortliffe 1976), but diagnosis of
engineered systems quickly surpassed medical diagnosis. There are probably more
diagnostic applications of ES than any other type. The diagnostic problem can be stated
in the abstract as: given the evidence presenting itself, what is the underlying
Planning and Scheduling
Systems that fall into this class analyze a set of one or more potentially complex and
interacting goals in order to determine a set of actions to achieve those goals, and/or
provide a detailed temporal ordering of those actions, taking into account personnel,
materiel, and other constraints. This class has great commercial potential, which has
been recognized. Examples involve airline scheduling of flights, personnel, and gates;
manufacturing job-shop scheduling; and manufacturing process planning.
Configuration of Manufactured Objects from Subassemblies
Configuration, whereby a solution to a problem is synthesized from a given set of
elements related by a set of constraints, is historically one of the most important of
expert system applications. Configuration applications were pioneered by computer
companies as a means of facilitating the manufacture of semi-custom minicomputers
(McDermott 1981). The technique has found its way into use in many different
industries, for example, modular home building, manufacturing, and other problems
involving complex engineering design and manufacturing.
Page | 6
Financial Decision Making
The financial services industry has been a vigorous user of expert system techniques.
Advisory programs have been created to assist bankers in determining whether to make
loans to businesses and individuals. Insurance companies have used expert systems to
assess the risk presented by the customer and to determine a price for the insurance. A
typical application in the financial markets is in foreign exchange trading.
This is a relatively new, but also potentially explosive area. The primary function of the
expert system is to deliver knowledge that is relevant to the user's problem, in the
context of the user's problem. The two most widely distributed expert systems in the
world are in this category. The first is an advisor which counsels a user on appropriate
grammatical usage in a text. The second is a tax advisor that accompanies a tax
preparation program and advises the user on tax strategy, tactics, and individual tax
Process Monitoring and Control
Systems falling in this class analyze real-time data from physical devices with the goal of
noticing anomalies, predicting trends, and controlling for both optimality and failure
correction. Examples of real-time systems that actively monitor processes can be found
in the steel making and oil refining industries.
Page | 7
Design and Manufacturing
These systems assist in the design of physical devices and processes, ranging from high-
level conceptual design of abstract entities all the way to factory floor configuration of
Two methods of reasoning when using inference rules are backward chaining and
Forward chaining starts with the data available and uses the inference rules to
conclude more data until a desired goal is reached. An inference engine using forward
chaining searches the inference rules until it finds one in which the if clause is known to
be true. It then concludes the then clause and adds this information to its data. It would
continue to do this until a goal is reached. Because the data available determines which
inference rules are used, this method is also called data driven.
Backward chaining starts with a list of goals and works backwards to see if
there is data which will allow it to conclude any of these goals. An inference engine using
backward chaining would search the inference rules until it finds one which has a then
clause that matches a desired goal. If the if clause of that inference rule is not known to
be true, then it is added to the list of goals.
Page | 8
Types of Expert Systems:
There are many different types of expert systems. The following list describes the
Diagnosis. Diagnosis types of expert systems are used to recommend remedies to
illnesses, trouble-shoot electronic or mechanical problems or as debugging tools.
Repair. Expert systems that define repair strategies are also very common. As well as
diagnosing the problem they can suggest a plan for the repair of the item. The repair plan
typically contains a scheduling structure and some control structure to validate the
repair process. Such systems have been employed in the automotive repair field and
Instruction. Instructional expert systems have been used for individualized training or
instruction in a particular field. The system presents material in an order determined by
its evaluation of the user’s ability and current knowledge and monitor’s the progress of
the student, altering the sequence depending on this progress.
Interpretation. Interpretive expert systems have the ability to analyze data to
determine its significance or usefulness. The knowledge base often contains models of
real world situations which it compares to its data. These are often used in exploration
for mineral, gas and oil deposits as well as in surveillance, image analysis and speech
Page | 9
Prediction. Predictive expert systems are used as a method to “guess” at the possible
outcomes of observed situations, usually providing a probability factor. This is used
often in weather forecasting.
Design and Planning. This allows experts to quickly develop solutions that save time.
These systems do not replace experts but act as a tool by performing tasks such as
costing, building design, material ordering and magazine design.
Monitoring and Control. In certain applications expert systems can be designed to
monitor operations and control certain functions. These are particularly useful where
speed of decision making is vitally important, for example in the nuclear energy industry,
air traffic control and the stock market.
Classification/Identification. These systems help to classify the goals in the system by
the identification of various features (these can by physical or non-physical) For example
various types of animals are classified according to attributes such as habitat, feeding
information, colour, breeding information, relative size etc. These systems can be used
by bird watchers, fishing enthusiasts, animal rescue shelters (to match animals to
prospective owners) to name a few
Expert System and Artificial Intelligence:
Expert Systems are computer programs that are derived from a branch of
computer science research called Artificial Intelligence (AI). AI's scientific goal is to
understand intelligence by building computer programs that exhibit intelligent behavior.
Page | 10
It is concerned with the concepts and methods of symbolic inference, or reasoning, by a
computer, and how the knowledge used to make those inferences will be represented
inside the machine.
Of course, the term intelligence covers many cognitive skills, including the
ability to solve problems, learn, and understand language; AI addresses all of those. But
most progress to date in AI has been made in the area of problem solving -- concepts and
methods for building programs that reason about problems rather than calculate a
AI programs that achieve expert-level competence in solving problems in task
areas by bringing to bear a body of knowledge about specific tasks are called knowledge-
based or expert systems. Often, the term expert systems is reserved for programs whose
knowledge base contains the knowledge used by human experts, in contrast to
knowledge gathered from textbooks or non-experts. More often than not, the two terms,
expert systems (ES) and knowledge-based systems (KBS), are used synonymously.
Taken together, they represent the most widespread type of AI application. The area of
human intellectual endeavor to be captured in an expert system is called the task
domain. Task refers to some goal-oriented, problem-solving activity. Domain refers to the
area within which the task is being performed. Typical tasks are diagnosis, planning,
scheduling, configuration and design.
Building an expert system is known as knowledge engineering and its
practitioners are called knowledge engineers. The knowledge engineer must make sure
that the computer has all the knowledge needed to solve a problem. The knowledge
engineer must choose one or more forms in which to represent the required knowledge
as symbol patterns in the memory of the computer -- that is, he (or she) must choose a
Page | 11
knowledge representation. He must also ensure that the computer can use the knowledge
efficiently by selecting from a handful of reasoning methods. The practice of knowledge
engineering is described later. We first describe the components of expert systems.
The Building Blocks of Expert Systems:
Every expert system consists of two principal parts: the knowledge base; and
the reasoning, or inference, engine.
The knowledge base of expert systems contains both factual and heuristic
knowledge. Factual knowledge is that knowledge of the task domain that is widely
shared, typically found in textbooks or journals, and commonly agreed upon by those
knowledgeable in the particular field.
Heuristic knowledge is the less rigorous, more experiential, more judgmental
knowledge of performance. In contrast to factual knowledge, heuristic knowledge is
rarely discussed, and is largely individualistic. It is the knowledge of good practice, good
judgment, and plausible reasoning in the field. It is the knowledge that underlies the "art
of good guessing."
Knowledge representation formalizes and organizes the knowledge. One
widely used representation is the production rule, or simply rule. A rule consists of an IF
part and a THEN part (also called a condition and an action). The IF part lists a set of
conditions in some logical combination. The piece of knowledge represented by the
production rule is relevant to the line of reasoning being developed if the IF part of the
rule is satisfied; consequently, the THEN part can be concluded, or its problem-solving
action taken. Expert systems whose knowledge is represented in rule form are called
Page | 12
Another widely used representation, called the unit (also known as frame,
schema, or list structure) is based upon a more passive view of knowledge. The unit is an
assemblage of associated symbolic knowledge about an entity to be represented.
Typically, a unit consists of a list of properties of the entity and associated values for
Since every task domain consists of many entities that stand in various relations,
the properties can also be used to specify relations, and the values of these properties
are the names of other units that are linked according to the relations. One unit can also
represent knowledge that is a "special case" of another unit, or some units can be "parts
of" another unit.
The problem-solving model, or paradigm, organizes and controls the steps
taken to solve the problem. One common but powerful paradigm involves chaining of IF-
THEN rules to form a line of reasoning. If the chaining starts from a set of conditions and
moves toward some conclusion, the method is called forward chaining. If the conclusion
is known (for example, a goal to be achieved) but the path to that conclusion is not
known, then reasoning backwards is called for, and the method is backward chaining.
These problem-solving methods are built into program modules called inference engines
or inference procedures that manipulate and use knowledge in the knowledge base to
form a line of reasoning.
The knowledge base an expert uses is what he learned at school, from colleagues,
and from years of experience. Presumably the more experience he has, the larger his
store of knowledge. Knowledge allows him to interpret the information in his databases
to advantage in diagnosis, design, and analysis.
Page | 13
Though an expert system consists primarily of a knowledge base and an inference
engine, a couple of other features are worth mentioning: reasoning with uncertainty, and
explanation of the line of reasoning.
Knowledge is almost always incomplete and uncertain. To deal with uncertain
knowledge, a rule may have associated with it a confidence factor or a weight. The set of
methods for using uncertain knowledge in combination with uncertain data in the
reasoning process is called reasoning with uncertainty. An important subclass of methods
for reasoning with uncertainty is called "fuzzy logic," and the systems that use them are
known as "fuzzy systems."
Because an expert system uses uncertain or heuristic knowledge (as we humans
do) its credibility is often in question (as is the case with humans). When an answer to a
problem is questionable, we tend to want to know the rationale. If the rationale seems
plausible, we tend to believe the answer. So it is with expert systems. Most expert
systems have the ability to answer questions of the form: "Why is the answer X?"
Explanations can be generated by tracing the line of reasoning used by the inference
engine (Feigenbaum, McCorduck et al. 1988).
The most important ingredient in any expert system is knowledge. The power of
expert systems resides in the specific, high-quality knowledge they contain about task
domains. AI researchers will continue to explore and add to the current repertoire of
knowledge representation and reasoning methods. But in knowledge resides the power.
Because of the importance of knowledge in expert systems and because the current
knowledge acquisition method is slow and tedious, much of the future of expert systems
depends on breaking the knowledge acquisition bottleneck and in codifying and
representing a large knowledge infrastructure.
Page | 14
It is the art of designing and building expert systems, and knowledge engineers
are its practitioners. Gerald M. Weinberg said of programming in The Psychology of
Programming: "'Programming,' -- like 'loving,' -- is a single word that encompasses an
infinitude of activities" (Weinberg 1971). Knowledge engineering is the same, perhaps
more so. We stated earlier that knowledge engineering is an applied part of the science
of artificial intelligence which, in turn, is a part of computer science. Theoretically, then,
a knowledge engineer is a computer scientist who knows how to design and implement
programs that incorporate artificial intelligence techniques. The nature of knowledge
engineering is changing, however, and a new breed of knowledge engineers is emerging.
We'll discuss the evolving nature of knowledge engineering later.
Today there are two ways to build an expert system. They can be built from
scratch, or built using a piece of development software known as a "tool" or a "shell."
Before we discuss these tools, let's briefly discuss what knowledge engineers do. Though
different styles and methods of knowledge engineering exist, the basic approach is the
same: a knowledge engineer interviews and observes a human expert or a group of
experts and learns what the experts know, and how they reason with their knowledge.
The engineer then translates the knowledge into a computer-usable language, and
designs an inference engine, a reasoning structure, that uses the knowledge
appropriately. He also determines how to integrate the use of uncertain knowledge in
the reasoning process, and what kinds of explanation would be useful to the end user.
Next, the inference engine and facilities for representing knowledge and for
explaining are programmed, and the domain knowledge is entered into the program
piece by piece. It may be that the inference engine is not just right; the form of
Page | 15
knowledge representation is awkward for the kind of knowledge needed for the task;
and the expert might decide the pieces of knowledge are wrong. All these are discovered
and modified as the expert system gradually gains competence.
The discovery and cumulation of techniques of machine reasoning and
knowledge representation is generally the work of artificial intelligence research. The
discovery and cumulation of knowledge of a task domain is the province of domain
experts. Domain knowledge consists of both formal, textbook knowledge, and
experiential knowledge -- the expertise of the experts.
An understanding of the "inference rule" concept is important to understand
expert systems. An inference rule is a statement that has two parts, an if clause and a
then clause. This rule is what gives expert systems the ability to find solutions to
diagnostic and prescriptive problems. An example of an inference rule is:
If the restaurant choice includes French, and the occasion is romantic,
Then the restaurant choice is definitely Paul Bocuse.
An expert system's rule base is made up of many such inference rules. They are
entered as separate rules and it is the inference engine that uses them together to draw
conclusions. Because each rule is a unit, rules may be deleted or added without affecting
other rules (though it should affect which conclusions are reached). One advantage of
inference rules over traditional programming is that inference rules use reasoning which
more closely resemble human reasoning.
Page | 16
Thus, when a conclusion is drawn, it is possible to understand how this conclusion
was reached. Furthermore, because the expert system uses knowledge in a form similar
to the expert, it may be easier to retrieve this information from the expert.
Individuals involved with expert systems:
There are generally three individuals having an interaction with expert
systems. Primary among these is the end-user; the individual who uses the system for its
problem solving assistance. In the building and maintenance of the system there are two
other roles: the problem domain expert who builds and supplies the knowledge base
providing the domain expertise, and a knowledge engineer who assists the experts in
determining the representation of their knowledge, enters this knowledge into an
explanation module and who defines the inference technique required to obtain useful
problem solving activity. Usually, the knowledge engineer will represent the problem
solving activity in the form of rules which is referred to as a rule-based expert system.
When these rules are created from the domain expertise, the knowledge base stores the
rules of the expert system.
Expert systems versus problem-solving systems:
The principal distinction between expert systems and traditional problem
solving programs is the way in which the problem related expertise is coded. In
traditional applications, problem expertise is encoded in both program and data
structures. In the expert system approach all of the problem related expertise is encoded
in data structures only; no problem-specific information is encoded in the program
structure. This organization has several benefits.
Page | 17
An example may help contrast the traditional problem solving program with the
expert system approach. The example is the problem of tax advice. In the traditional
approach data structures describe the taxpayer and tax tables, and a program in which
there are statements representing an expert tax consultant's knowledge, such as
statements which relate information about the taxpayer to tax table choices. It is this
representation of the tax expert's knowledge that is difficult for the tax expert to
understand or modify.
In the expert system approach, the information about taxpayers and tax
computations is again found in data structures, but now the knowledge describing the
relationships between them is encoded in data structures as well. The programs of an
expert system are independent of the problem domain (taxes) and serve to process the
data structures without regard to the nature of the problem area they describe. For
example, there are programs to acquire the described data values through user
interaction, programs to represent and process special organizations of description, and
programs to process the declarations that represent semantic relationships within the
problem domain and an algorithm to control the processing sequence and focus.
The general architecture of an expert system involves two principal components: a
problem dependent set of data declarations called the knowledge base or rule base, and
a problem independent (although highly data structure dependent) program which is
called the inference engine.
Types of problems solved by expert systems:
Expert systems are most valuable to organizations that have a high-level of know-
how experience and expertise that cannot be easily transferred to other members. They
Page | 18
are designed to carry the intelligence and information found in the intellect of experts
and provide this knowledge to other members of the organization for problem-solving
Typically, the problems to be solved are of the sort that would normally be
tackled by a medical or other professional. Real experts in the problem domain (which
will typically be very narrow, for instance "diagnosing skin conditions in human
teenagers") are asked to provide "rules of thumb" on how they evaluate the problems,
either explicitly with the aid of experienced systems developers, or sometimes implicitly,
by getting such experts to evaluate test cases and using computer programs to examine
the test data and (in a strictly limited manner) derive rules from that. Generally, expert
systems are used for problems for which there is no single "correct" solution which can
be encoded in a conventional algorithm — one would not write an expert system to find
shortest paths through graphs, or sort data, as there are simply easier ways to do these
Simple systems use simple true/false logic to evaluate data. More sophisticated
systems are capable of performing at least some evaluation, taking into account real-
world uncertainties, using such methods as fuzzy logic. Such sophistication is difficult to
develop and still highly imperfect
Provides consistent answers for repetitive decisions, processes and tasks
Holds and maintains significant levels of information
Encourages organizations to clarify the logic of their decision-making
Always asks a question, that a human might forget to ask
Page | 19
Can work continuously (no human needs)
Can be used by the user more frequently
A multi-user expert system can serve more users at a time
Lacks common sense needed in some decision making
Cannot respond creatively like a human expert would in unusual circumstances
Domain experts not always able to explain their logic and reasoning
Errors may occur in the knowledge base, and lead to wrong decisions
Cannot adapt to changing environments, unless knowledge base is changed
Benefits to End Users:
Primarily, the benefits of ES’s to end users include:
A speed-up of human professional or semi-professional work -- typically by a
factor of ten and sometimes by a factor of a hundred or more.
Within companies, major internal cost savings. For small systems, savings are
sometimes in the tens or hundreds of thousands of dollars; but for large systems,
often in the tens of millions of dollars and as high as hundreds of millions of
dollars. These cost savings are a result of quality improvement, a major motivation
for employing expert system technology.
Improved quality of decision making. In some cases, the quality or correctness of
decisions evaluated after the fact show a ten-fold improvement.
Page | 20
Preservation of scarce expertise. ES’s are used to preserve scarce know-how in
organizations, to capture the expertise of individuals who are retiring, and to
preserve corporate know-how so that it can be widely distributed to other
factories, offices or plants of the company.
Introduction of new products. A good example of a new product is a pathology
advisor sold to clinical pathologists in hospitals to assist in the diagnosis of
Expert Systems in Education:
In education field, many of the expert system’s application are embedded inside the
Intelligent Tutoring System (ITS) by using techniques from adaptive hypertext and
hypermedia. Most of the system usually will assist student in their learning by using
adaptation techniques to personalize with the environment, prior knowledge of student
and student’s ability to learn.
In term of technology used, expert system in education has expanded very consistently
from microcomputer to web based (Woodin D.E, 2001) and agent-based expert system
(Vivacqua A., and Lieberman H., 2000). By using web-based expert system, it can provide
an excellent alterative to private tutoring at anytime from anyplace (Markham H.C,
2001) where Internet is provided. Also, agent based expert system surely will help users
by finding materials from the web based on the user’s profile. Supposedly, agent expert
system should have capability to diagnose the users and giving the results according to
Page | 21
Besides technology used, expert system also had a tremendous changes in the applying
of methods and techniques. Starting from a simple rule based system; currently expert
system techniques had adapted a fuzzy logic (Michael Starek, Mukesh Tomer, Krishna
Bhaskar, and Mario Garcia ,2002) and hybrid based technique (Jim Prentzas, Ioannis
Hatzilygeroudis, C. Koutsojannis , 2001).
Needs for Expert Systems in Education:
According to Markham H.C (2001), expert system are beneficial as a teaching tools
because it has equipped with the unique features which allow users to ask question on
how, why and what format. When it used in the class environment, surely it will gave
many benefit to student as it prepare the answer without referring to the teacher. Beside
that, expert system is able to a give reasons towards the given answer. This features is
really great as it can make students more understand and confident with the answer.
Ability of expert system to adaptively adjust the training for each particular student on
the bases of his/her own pace of learning is another feature that makes expert system
more demanding for students. This feature is used in (Zorica Nedic, Vladimir Nedic and
Jan Machotka, 2002) for teaching engineering students. It should be able to monitor
student’s progress and make a decision about the next step in training.
Page | 22
Knowledge Acquisition in Expert System:
The system must liaise with people in order to gain knowledge and the people must be
specialized in the appropriate area of activity. For example medical doctors, geologists or
chemists. The knowledge engineer acts as an intermediary between the specialist and
the expert system. Typical of the information that must be gleaned is vocabulary or
jargon, general concepts and facts, problems that commonly arise, the solutions to the
problems that occur and skills for solving particular problems. This process of picking
the brain of an expert is a specialized form of data capture and makes use of interview
Page | 23
Page | 24
Prolog is a general purpose logic programming language associated with artificial
intelligence and computational linguistics.
Prolog has its roots in formal logic, and unlike many other programming languages,
Prolog is declarative: The program logic is expressed in terms of relations, represented
as facts and rules. Execution is triggered by running queries over these relations.
Prolog was one of the first logic programming languages, and remains among the most
popular such languages today, with many free and commercial implementations
available. While initially aimed at natural language processing, the language has since
then stretched far into other areas like theorem proving, expert systems, games,
automated answering systems, ontologies and sophisticated control systems. Modern
Prolog environments support the creation of graphical user interfaces, as well as
administrative and networked applications.
Programming in Prolog:
In Prolog, program logic is expressed in terms of relations, and execution is triggered by
running queries over these relations. Relations and queries are constructed using
Prolog's single data type, the term. Relations are defined by clauses. Given a query, the
Prolog engine attempts to find a resolution refutation of the negated query. If the
negated query can be refuted, i.e., an instantiation for all free variables is found that
makes the union of clauses and the singleton set consisting of the negated query false, it
follows that the original query, with the found instantiation applied, is a logical
consequence of the program. This makes Prolog (and other logic programming
Page | 25
languages) particularly useful for database, symbolic mathematics, and language parsing
applications. Because Prolog allows impure predicates, checking the truth value of
certain special predicates may have some deliberate side effect, such as printing a value
to the screen. This permits the programmer to use some amount of conventional
imperative programming when the logical paradigm is inconvenient. It has a purely
logical subset, called "pure Prolog", as well as a number of extralogical features.
Prolog's single data type is the term. Terms are atoms, numbers, variables or compound
An atom is a general-purpose name with no inherent meaning. Examples of atoms
include x, blue, 'Taco', and 'some atom'.
Numbers can be floats or integers.
Variables are denoted by a string consisting of letters, numbers and underscore
characters, and beginning with an upper-case letter or underscore. Variables
closely resemble variables in logic in that they are placeholders for arbitrary
A compound term is composed of an atom called a "functor" and a number of
"arguments", which are again terms. Compound terms are ordinarily written as a
functor followed by a comma-separated list of argument terms, which is contained
in parentheses. The number of arguments is called the term's arity. An atom can be
regarded as a compound term with arity zero. Special cases of compound terms:
Page | 26
A List is an ordered collection of terms. It is denoted by square brackets with the
terms separated by commas or in the case of the empty list, . For example [1,2,3]
Strings: A sequence of characters surrounded by quotes is equivalent to a list of
(numeric) character codes, generally in the local character encoding or Unicode if
the system supports Unicode. For example, "to be, or not to be".
Rules and facts:
Prolog programs describe relations, defined by means of clauses. Pure Prolog is
restricted to Horn clauses, a Turing-complete subset of first-order predicate logic. There
are two types of clauses: Facts and rules. A rule is of the form
Head :- Body.
and is read as "Head is true if Body is true". A rule's body consists of calls to predicates,
which are called the rule's goals. The built-in predicate ,/2 (meaning a 2-arity operator
with name ,) denotes conjunction of goals, and ;/2 denotes disjunction. Conjunctions and
disjunctions can only appear in the body, not in the head of a rule.
Clauses with empty bodies are called facts. An example of a fact is:
which is equivalent to the rule:
cat(tom) :- true.
The built-in predicate true/0 is always true.
Page | 27
Given the above fact, one can ask:
is tom a cat?
what things are cats?
X = tom
Due to the relational nature of many built-in predicates, they can typically be used in
several directions. For example, length/2 can be used to determine the length of a list
(length(List, L), given a list List) as well as to generate a list skeleton of a given length
(length(X, 5)), and also to generate both list skeletons and their lengths together
(length(X, L)). Similarly, append/3 can be used both to append two lists (append(ListA,
ListB, X) given lists ListA and ListB) as well as to split a given list into parts (append(X, Y,
List), given a list List). For this reason, a comparatively small set of library predicates
suffices for many Prolog programs. All predicates can also be used to perform unit tests:
Queries can be embedded in programs and allow for automatic compile-time regression
As a general purpose language, Prolog also provides various built-in predicates to
perform routine activities like input/output, using graphics and otherwise
communicating with the operating system. These predicates are not given a relational
meaning and are only useful for the side-effects they exhibit on the system. For example,
the predicate write/1 displays a term on the screen.
Page | 28
The following queries yield the specified answers.
| ?- likes(mary,food).
| ?- likes(john,wine).
| ?- likes(john,food).
Data Structures and Syntax:
We have already seen how prolog programs consist of facts, rules and questions. Facts
declare things that are always true. Rules declare things that are true depending on some
conditions. They consist of a head and a body. For example the rule ``a(X) :- b(X), c(X).''
has head ``a(X)'' and body ``b(X), c(X)''. Its head is true if the goals in its body are all true.
(Facts can be viewed as rules without a body). Facts and/or rules can be used to define
relations (or predicates). These can be of different arities (ie, have different numbers of
arguments). For example, lectures/2 is the binary relation lectures, and might be defined
Page | 29
by the three facts lectures(alison, ai), tt lectures(phil, databases), and lectures(gilbert,
Questions are used to find out if something is true (and what the associated variable
bindings would be to make it true). Facts, rules and questions are all prolog clauses and
must end with a full stop.
The fundamental data structure in Prolog is the term. Prolog terms include:
such as sparrow, x, 'Alison Cawsey', a102, -. These generally represent specific single
entities in the world and cannot be separated into parts. They normally begin with a
lower-case letter, but arbitrary characters can be used if they are quoted. Symbols (such
as ``-'') and sequences of symbols (e.g., ``:-'') are also atoms.
such as 29, 1.2, 3000, -2.
such as X, Person, _Var. Variables begin either with a capital letter or an underline
As we have seen, Prolog tries to prove (answer) a query by looking for facts which match
that query, or rules whose heads match the query and whose body can be proved. The
way prolog matches terms is therefore crucial.
Page | 30
We have already seen how simple expressions such as lectures(alison,Course) can be
matched to facts such as lectures(alison, ai) resulting in bindings such as Course=ai. In
the above section we saw examples of a slightly more complex match, where terms with
complex arguments were matched against each other, so
Name = lord_of_the_rings
Author = tolkien
Prolog matches expressions in a purely structural way, with no evaluation of
?- 1+2 = 3
[Note: In prolog ``='' means ``matches with''. You can test matches by typing in queries
such as the one above.]
Similarly the following won't match, as the two expressions have different structures:
Page | 31
?- X + 2 = 3 * Y.
However, the following match as they have the same structure:
?- X+Y = 1+2.
?- 1+Y = X + 3.
Note that there can be variables in both sides of a matched expression, as in the second
For non-arithmetic examples, we have:
?- lectures(X, ai) = lectures(alison, Y).
X = alison
Y = ai
?- book(title(X), author(Y)) = book(Z, author(tolkien)).
Z = title(X)
Y = tolkien
Page | 32
At this point we should go through in more detail how Prolog answers queries (and
therefore runs programs). Given a query to prove (answer), Prolog goes down its list of
facts and rules, from top to bottom, looking for facts or rule heads which match the query
(given any existing variable bindings). When it finds one, it stores the place in the
fact/rule base it had got to in its search, so if the first match it finds is no good it can
carry on and look for more possibilities. So, suppose we have the facts:
and give the query ?- bird(type(penguin), name(X)). Prolog will first try matching the
query with the first fact, but fail because sparrow doesn't match penguin. It will then try
matching with the second fact, and succeed with X = tweety. However, it will put a
pointer to the place it got to, so if it turns out that a later query/subgoal fails, it will go
back to the saved position, and look for more solutions (ie, X = percy).
So, if we had a fact/rule base such as:
Page | 33
bird(X) :- animal(X), has_feathers(X).
tame_bird(X) :- bird(X), tame(X).
and gave the query bird(Bird) , then Prolog would go down the facts and rules until it
reached the first rule, and would match bird(Bird) against bird(X). The variable Bird
would then be instantiated to the variable X. Prolog then tries to prove the body of the
rule. The subgoal animal(X) succeeds with X=leo. Prolog keeps a pointer of how far its
got in checking for animal(X), and tries has_feathers(leo). It goes down the facts/rules
looking for one that matches, but doesn't find anything. It therefore goes back to the last
thing it tried to match (animal(X)), starts from where it left off, and matches with
animal(tweety). But has_feathers(tweety) still doesn't match. So it goes back again and
finds animal(percy). has_feathers(percy) matches, so the whole thing succeeds, with
final bindings Bird = percy.
Now, if we give the query tame_bird(B), things get a little more complex. Prolog first tries
to satisfy bird(X) as above. But then tame(percy) fails. It therefore has to try to resatisfy
bird(X). It will do this by first trying to resatisfy has_feathers(percy) as that was the last
goal it tried. But there is no other way of satisfying it. So it goes back yet again to
animal(X), finding X = peter. has_feathers(peter) succeeds, so bird(X) can succeed a
second way with X = peter. tame(peter) succeeds, so tame_bird(B) succeeds with B =
In the above example, prolog is just bactracking through facts. But in general there may
be more than one rule which prolog could try, for example:
Page | 34
animal(percy). % fact1
has_feathers(percy). % fact2
penguin(tweety). % fact3
penguin(peter). % fact4
tame(peter). % fact5
bird(X) :- % rule1
bird(X) :- % rule2
tame_bird(X) :- % rule3
Given a query bird(B) prolog would first use the first rule (and third fact) and get
B=tweety. If it then had to backtrack it would match penguin(X) with the fourth fact to
get B = peter. If it bactracks again it will run out of penguin clauses so have to try the
second bird rule, and (using the first and second fact) get B = percy. So, remembering
that you can type a ``;'' (or click on ``next'') to force backtracking, we get:
B = tweety ;
B = peter ;
B = percy ;
Page | 35
Declarative and Procedural Views of Programs:
At this point it is worth thinking a bit about what Prolog programs mean. There are
generally two ways to look at any Prolog rule - as a declarative statement about what is
true, or as a procedural statement about how to do something. One of the claimed
advantages of Prolog is that it is often possible to think of programs purely declaratively.
How Prolog proves things should be of less concern. However, for any reasonably
complex program, as we discussed earlier, it often becomes important to think about
how it executes the program. For example, the order of subgoal execution may be crucial
to the efficiency of the program, and variables may be used in a way that does not have a
simple declarative reading. Prolog also allows non-logical statements, like write
statements and assertions. When these are included in a program it becomes even more
important to think about what Prolog is doing.
To state a bit more clearly what we mean by declarative and procedural readings of
programs, if we have a rule:
p :- q, r.
The declarative reading is: ``p is true if q is true and r is true''. The procedural reading
can be stated as ``to solve problem p, first solve problem q and then solve problem r'', or
alternatively ``to satisfy p, first satisfy q and then r''.
The recursion in any language is a function that can call itself until the goal has been
In Prolog, recursion appears when a predicate contain a goal that refers to itself.
Page | 36
As we have seen in the earlier chapters when a rule is called Prolog create a new query
with new variables. So it makes no difference whether a rule calls another rule or call
In Prolog and in any language, a recursive definition always has at least two parts. A first
fact that act like a stopping condition and a rule that call itself simplified. At each level
the first fact is checked. If the fact is true then the recursion ends. If not the recursion
A recursive rule must never call itself with the same arguments ! If that happens then the
program will never end.
The best way in Prolog to calculate a factorial is to do it recursivelly. Here is an example
of how it can be done :
X1 is X - 1,
Y is Z*X,!.
Note that in this case the cut is not necessary, it means that there is only one solution.
The message ''Out of local stack'' may appear if you press ';' after the first solution. Now
if you enter :
X = 120
Page | 37
In this example Prolog will try to calculate 5! then 4! then 3! until it has to calculate 0!,
then the result will be 0!*1*2*3*4*5. Prolog will respond 120.
It has built-in list handling, very useful for representing sequences, trees, and so
It is easy to read and write programs which build structures.
add( complex(A,B), complex(C,D),
E is A+C,
F is B+D.
Most Prologs nowadays should be able to handle structures of at least 30Kbytes in
Although Prolog is not a complete implementation of logic, it is much closer to it
than C, and is more like mathematical notation.
It is easy to build tables and databases while a program is running, as I did with
memo_fib. You don't need a lot of programming effort.
You can reason about programs as algebraic objects. When writing a predicate,
begin with a definition that is obviously correct, but inefficient. Then apply
transformations that preserve its effect while making it more efficient.
Page | 38
It tempts you to write things that look logically correct, but that won't run.
The obvious way to write a predicate is unlikely to be efficient. You must know
when a predicate needs to be optimised.
Because it lacks functional notation, predicates can become cumbersome.
f( N, F ) :-
N1 is N - 1,
f( N1, F1 ),
F is N * F1.
It would be much nicer to write
f( N ) = N * f(N-1).
Input and output is not always easy.
There are some features which have not been standardised, and differ between
implementations. For example: formatted input and output, file-handling, sorting
You can't re-assign to parts of data structures. This makes it impossible to
implement arrays. However, functional programmers have developed a number of
fast-access data structures which do almost as good a job.
Accumulators are the variables used to store intermediate values may be integer or list.
Page | 39
It is useful if we need to inspect some intermediate results.
It avoids wasteful joining of structures during concatenation, thus making the
operation less expensive.
It increases the efficiency of the program.
It always produces in list in reverse order.
It is a technique or method in which we represent the list as a difference of two
incomplete lists or list having holes.
It improves the efficiency of the program.
It avoids the wasteful joining of structure.
It produces the list in same order as the original list.
It is not so flexible.
It is complex as compared to the accumulators.
Page | 40
Page | 41
Introduction to ‘Car Failure Diagnosis’:-
Fault diagnosis has become a very important area of research during the last decade due
to the advancement of mechanical and electrical systems. The automobile is a crucial
field where fault diagnosis is given a special attention. Due to the increasing complexity
and newly added features in vehicles, a comprehensive study has to be performed in
order to achieve an appropriate diagnosis model. A diagnosis system is capable of
identifying the faults of a system by investigating the observable effects (or
symptoms).Expert System is a branch of artificial intelligence, which studies the field of
developing and implementing computer programs that can act and work on the lines of
human brain which can acquire knowledge and develop intelligence of its own to act
accordingly in situations that may be entirely or partially new to it.
“Car Failure Diagnosis” is a project which is made in PROLOG, which is a computer
programming language used for symbolic representations and non-numeric
computations. It is a project which is used to diagnose a faults in car. It asks the user a
series of yes/no questions to decide what the issue is and then goes on to suggest
various methods to work out a solution.
This project aims to provide an aid to anyone who is facing some problems in computer
functionality. Following are the four domains of problems addressed:-
Car Ignition Problems
Engine Problems after Ignition
Mechanical Part Working
Page | 42
The information from the user is gathered by the means of a yes/no questionnaire.
It starts with asking the user whether his/her car starts or not. If it does not start, the
user enters ‘n’ and he is guided about various ways to deal with the problem. After each
step the user is asked whether his problem has been resolved. If at any step user
declares that his problem has been solved the troubleshooter terminates. If after all
suggestions the problem yet remains unresolved then the troubleshooter fails. It gives
out a message of apology and halts.
If the user problem is about some other issue than the above mentioned domain
then the troubleshooter goes on to question the user about the remaining domains
Page | 43
Page | 44
Page | 45
^Turbo Prolog Version 1.1
Page | 46
^Car does not start
Page | 47
^Engine Problem After Ignition
Page | 48
^Mechanical Parts Working Issue
Page | 49
^Troubleshooter Fails !!!
Page | 50
It is recommended that the minimum configuration for clients is as appended below:-
Suggested Configuration of Windows clients:-
Microprocessor - Pentium-4 class processor or above, 450 megahertz (MHz)
RAM - 256 MB of RAM
Hard Disk - 5 gigabytes (GB) on installation
CD ROM Drive – 16x CD-ROM Drive
Windows 98 / XP operating system
Page | 51
BIBLIOGRAPHY AND REFRENCES
Programming in PROLOG by W.F Clocksin C.S Mellish.
Introduction to Artificial Intelligence and Expert System by Dan W.Patterson.
Page | 52