Professional Documents
Culture Documents
Dec 2008 PDF
Dec 2008 PDF
C R O S S
+ R O A D S
D E N G E R
Ans :
You see that the D in DANGER must have been carried over from the addition of C and R in CROSS
and ROADS, respectively. Thus, we have:
CROSS
+ROA1S
------------
1ANGER
This, by some fairly weird algebra and modular arithmetic, leads to the following relationships:
R = 2S mod 10
E = (3S + 1 - (2S mod 10)) mod 10
A = (C + 2R - (R + O mod 10)) mod 10
A = G - O mod 10
N = (R + 2O - (O + A mod 10)) mod 10
C = A - R mod 10
O = N - R mod 10
O = G - A mod 10
G = (O + A + S + 1 - (S + 1 mod 10)) mod 10
12344
+25614
------
3NO! D has to be 1
92344
+25614
------
11NO! A cannot be 1 because D is 1
96233
+62513
------
158746
Ans:
A monkey is in a cage and bananas are suspended from the ceiling, the monkey
wants to eat a banana but cannot reach them
in the room are a chair and a stick
if the monkey stands on the chair and waves the stick, he can knock a banana
down to eat it
Initial state:
Goal state:
Actions:
grab X
wave X
eat X
(ii) Water Jug problem
The state space for this problem can be described as the set of ordered pairs of
integers (x, y) such that x = 0, 1,2, 3 or 4 and y = 0,1,2 or 3; x represents the number of
gallons of water in the 4-gallon jug and y represents the quantity of water in 3-gallon jug
3 (x, y) if x > 0 (x-d, y) Pour some water out of the 4 gallon jug
4 (x, y) if y > 0 (x, y-d) Pour some water out of the 3-gallon jug
7 (x, y) if x + y (4, y-(4-x)) Pour water from the 3 gallon jug into the 4
>= 4 and y >0 gallon jug until the 4-gallon jug is full
8 (x, y) if x + y (x-(3-y), 3) Pour water from the 4-gallon jug into the 3-
>= 3 and x>0 gallon jug until the 3-gallon jug is full
9 (x, y) if x + y (x + y, 0) Pour all the water from the 3-gallon jug into the
<=4 and y>0 4-gallon jug
10 (x, y) if x + y (0, x + y) Pour all the water from the 4-gallon jug into the
<= 3 and x>0 3-gallon jug
11 (0,2) (2,0) Pour the 2 gallons from 3-gallon jug into the 4-
gallon jug
Required a control structure that loops through a simple cycle in which some
rule whose left side matches the current state is chosen, the appropriate change
to the state is made as described in the corresponding right side, and the
resulting state is checked to see if it corresponds to goal state.
One solution to the water jug problem
0 0 2
0 3 9
3 0 2
3 3 7
4 2 5 or 12
0 2 9 0r 11
2 0
1 2 3
8 4
7 6 5
2 8 3
1 6 4
7 5
Ans :
2 8 3
1 6 4
2 8 3
7 5 Right 3
Left 1 1 6 4
Up 2
2 8 3
7 5 7 5
1 6 4 2 8 3
1 4
7 6 5
2 8 3
Left 1 1 6 4
7 5
Up 1.1
2 8 3
6 4
1 7 5
UP 2
2 8 3
1 4
7 6 5
2 3
2 8 3
1 8 4
Left 2.1 1 4 Up 2.2 Right 2.3 2 8 3
7 6 5
7 6 5 1 4
7 6 5
Right 3
2 8 3
1 6 4
7 5
Up 3.1 2 8 3
1 6
7 5 4
Up 1.1
2 8 3
6 4
1 7 5
Right 2 8 3
8 3 1.1.2
6 4
2 6 4 1 7 5
2 8 3
1 4
Left 2.1
7 6 5
2 8 3
8 3 Down 7 1 4
Up 2.1.2
2.1.1 2 1 4 6 5
7 6 5
2 3
Up 2.2
1 8 4
7 6 5
Left 2 3 Right 2 3
2.2.1 1 8 4 2.2.2 1 8 4
7 6 5 7 6 5
Right 2.3 2 8 3
1 4
7 6 5
Down 2.3.2
Up 2.3.1
2 8 3
2 8
1 4 5
1 4 3
7 6
7 6 5
2 8 3
Up 3.1 1 6
7 5 4
2 8 3
Up 2 8
Left 1 6 3.1.2 1 6 3
3.1.1
7 5 4
7 5 4
Up 8 3
1.1.1 2 6 4
1 7 5
Right
1.1.1.1
8 3
2 6 4
1 7 5
2 8 3
Right
6 4
1.1.2
1 7 5
Right Down
1.1.2.2 2 8 3 1.1.2.3 2 8 3
2 3
6 4 6 7 4
6 8 4
1 7 5 1 5
2 3
Left 1 8 4
2.2.1
7 6 5
1 2 3
Down
2.2.1.1 8 4
7 6 5
Right
2.2.1.1.1 Down
1 2 3 1 2 3
2.2.1.1.2
8 4 7 8 4
7 6 5 6 5
Q-2
We can solve this problem by breaking it down into three smaller problems;
each of which we can then solve by using a small collection of specific rules.
Figure-2;9 shows the problem tree that will be generated by the process of
problem decomposition as it can be exploited by a simple recursive integration
program that worksras follows: At each step, it checks tojsee whether the
problem if is working on is immediately solvable.' If-so, then the answer is
returned directly. If the problem is not easily solvable, the integrator checks to
see whether it can decompose the problem into smaller problems. If it can, it
creates those problems and calls itself recursively on them. Using: thistechnique
of problem decomposition, we can often solvevery large problemseasily; v .
Now consider the problem illustrated in Figure 2.10. This problem is drawn
firom.the domain often referred to in AMiterature as the blocks world. Assume
that the following operators are available:
2 8 3 1 2 3
1 6 48 4
7 57 6 5
1. CLEARQc) [block x has nothing on it] -+ ON(JC, Table) [pick up x and put it
on the table]
2. CLEAR(x)andCLEAR(y)->ON(jt,;y) [put* on y]
These two examples, symbolic integration and the blocks world, illustrate the
difference between decomposable and nondecomposable problems. In Chapter.
3^ we present a specific algorithm for problem decomjposition, and in Chapter
13, we look at what happens when decomposition'is'impossible.
2. Otherwise, select the most important difference and reduce it by doing the
following until success or failure is signaled:
(c) If
(FIRST-PART <- MEAtCURRENT, O-START))
and
are successful, then signal success and return the result of concatenating
Many of the details of this process have been omitted in this discussion. In
particular, the order in which differences are considered can be critical. It is
important that significant differences be reduced before less critical ones. If this
is not done, a great deal of effort may be wasted on situations that take care of
themselves once the main parts of the problem are solved.
The simple process we have described is usually not adequate for solving
complex problems. The number of permutations of differences may get too
large. Working on one difference may interfere with the plan for reducing
another. And in complex worlds, the required difference tables would be
immense. In Chapter 13 we look at some ways in which the basic means-ends
analysis approach can be extended to tackle some of these problems.
Algorithm: Generate-and-Test
Unfortunately, for problems much harder than this, even heuristic generate-
and-test, all by itself, is not a very effective technique. Bat when combined
with other techniques to restrict the space in which to search even further, the
technique can be very effective.
1. Evaluate the initial state. If it is also a goal state, then return it and quit.
Otherwise, continue with the initial state as the current state.
2. Loop until a solution is found or until there are no new operators left to be
applied in the current state:
Select an operator that has riot yet been applied to the current state and apply
it to produce a new state.
Evaluate the new state, i. If it is a goal state, then return it and quit, ii. If it is
not a goal state but it is better than the current state, then make it
the current state, iii. If it is not better than the current state, then continue
in the loop.
The key difference between this algorithm and the one we gave for generate-
and test is the use of an evaluation function as a way to inject task-specific
knowledge into the control process. It is the use of such knowledge that makes
this and the other methods discussed in the rest of this chapter heuristic search
methods, and it is that same knowledge that gives these methods their power to
solve some otherwise intractable problems.
Notice that in this algorithm, we have asked the felativelvjrapue question, "Is
one state better than another?" For the algorithm to work, a precise definition
of better must be provided. In some cases, .it meiuis a higher value of the
heuristic function. In others, it means a lower value. It does not matter'which,
as long as a particular hill-climbing program is consistent in its interpretatidh."
To see how hill climbing works, let's return to the puzzle of the four colored
blocks. To solve the problem, we first need to define a heuristic function that
describes how close a particular configuration is to being a solution. One,such
function 1$ Simply the sum of the number of different colors on each of the four
sides. A solution to the puzzle will have a value of 16. Next we need to define a
set of rules that describe ways of transforming one configuration into another.
Actually, one rule will suffice. It says simply pick a block and rotate it 90
degrees in any direction. Having provided these definitions, the next step is to
generate a starting configuration. This can either be done at random or with the
aid of the heuristic function described in the last section. Now hill climbing can
begin. We generate a new state by selecting a block and rotating it. If the
resulting state is better, then we keep it. If not, we return to the previous state
and try a different perturbation.
No. Everything we need to know to prove the theorem is still, true and in
memory, if it ever was. Any rules that could have been applied at the outse?
can still be applied. We can just proceed as we should have in the first place.
All we have lost is the effort that was spent exploring the blind alley.
(a) Choose the most promising task from the agenda. Notice that this task
can be represented in any desired form. It can be thought of as an
explicit statement of what to do next or simply as an indication of the
next node to be expanded.
i. See if it is already on the agenda. If so, then see if this same reason
for doing it is already on its list of justifications. If so, ignore this
current evidence. If this justification was not already present, add it
to the list. If the task was not on the agenda, insert it.
ii. Compute the new task's rating, combining the evidence from all its
justifications. Not all justifications need have equal weight. It is often
useful to'associate with each justification a measure of how strong a
As you can see, the agenda mechanism provides a good way of focusing the
attention of a complex system in the areas suggested by the greatest number of
positive indicators. But the overhead for each task executed may be fairly high.
This raises the question of (he proper grain size for the division of the entire
problem-solving process into individual tasks. Suppose each task is very small.
Then we will never do even a very small thing unless it realjy is the best thing to
do. But we will spend a large percentage of our total effort on figuring out what
to do next. If, on the other hand, the size of an individual task is very large,
then some effort may be spent finishing one task when there are more
promising ones that could be done. But a smaller percentage of the total time
will be" spent on the overhead of figuring out what to do. The exact choice of
task size for a particular system depends on the extent to which doing one small
thing really means that a set of other small things is likely to be very good to do
too. It often requires some experimentation to get right.
Person: I don't want to read any more about China. Give me something ejse.
Computer: What things about Italy are you interested in reading about?
Q-3(a) Explain heuristic Search.
Ans:
Definition:
A Heuristic is an operationally-effective nugget of information on how to direct
search in a problem space. Heuristics are only approximately correct. Their purpose is to
minimize search on average.
Heuristic Search
General Form:
2. s-Queue:= F(Succ(Scurr),s-Queue)
3. Snext:= Argmax[E(s-Queue)]
Snext:= Argmax[E(Succ(Scurr))]
Max-Gradient Search
Snext:= Argmax[E(Succ(Scurr))]
Ans:
Intelligence:
Intelligence is the computational part of the ability to achieve goals in the world.
Varying kinds and degrees of intelligence occur in people, many animals and some machines.
Artificial Intelligence:
Ans:
Depth first search is another way of traversing graphs, which is closely related to preorder
traversal of a tree. Recall that preorder traversal simply visits each node before its children. It
is most easy to program as a recursive routine
BFS: This can be throught of as being like Dijkstra's algorithm for shortest paths, but with
every edge having the same length. However it is a lot simpler and doesn't need any data
structures. We just keep a tree (the breadth first search tree), a list of nodes to be added to the
tree, and markings (Boolean variables) on the vertices to tell whether they are in the tree or
list.
Q-3(d)(i)Construct The Semantic Net For The All Indian Likes Football
Q-3(e)
Ans:
A Tree structure is a way of representing the hierarchical nature of a structure in a graphical form. In
computer science, a tree is a widely-used data structure that emulates a hierarchical tree structure with
a set of linked nodes.
A node is a structure which may contain a value, a condition, or represent a separate data
structure (which could be a tree of its own). Each node in a tree has zero or more child nodes,
which are below it in the tree (by convention, trees are drawn growing downwards). A node
that has a child is called the child's parent node (or ancestor node, or superior). A node has at
most one parent.
Nodes that do not have any children are called leaf nodes. They are also referred to as
terminal nodes.
The topmost node in a tree is called the root node. Being the topmost node, the root node will
not have parents. It is the node at which operations on the tree commonly begin (although
some algorithms begin with the leaf nodes and work up ending at the root). All other nodes
can be reached from it by following edges or links. (In the formal definition, each such path
is also unique). In diagrams, it is typically drawn at the top. In some trees, such as heaps, the
root node has special properties. Every node in a tree can be seen as the root node of the
subtree rooted at that node.
An internal node or inner node is any node of a tree that has child nodes and is thus not a leaf
node. A sub tree of a tree T is a tree consisting of a node in T and all of its descendants in T.
Tree representations
There are many different ways to represent trees; common representations represent the
nodes as records allocated on the heap (not to be confused with the heap data structure) with
pointers to their children, their parents, or both, or as items in an array, with relationships
between them determined by their positions in the array
Process requests for service from system users and application layer modules;
Support the creation and modification of business rules by subject matter experts;
Translate business rules, created by a subject matter experts, into machine-readable
forms;
Execute business rules; and
Provide low-level support to expert system components (e.g., retrieve metadata from
and save metadata to knowledge base, build Abstract Syntax Trees during rule
translation of business rules, etc.).
The Client Interface processes requests for service from system-users and from application
layer components. Client Interface logic routes these requests to an appropriate shell
program unit. For example, when a subject matter expert wishes to create or edit a rule, they
use the Client Interface to dispatch the Knowledge-base Editor. Other service requests
might schedule a rule, or a group of rules, for execution by the Rule Engine.
The Knowledge-base Editor is a simple text editor, a graphical editor, or some hybrid of
these two types. It provides facilities that enable a subject matter expert to compose and add
rules to the Knowledge-base.
The translation of rules in their original form to a machine-readable form requires parsing the
textual representation to obtain a data structure referred to as an Abstract Syntax Tree
(AST). The AST representation of rules is the memory-resident data structure that guides
execution of the inference engine when it comes time to apply a rule. The AST is an abstract
data type designed to make its interpretation by the Rule Engine simple and efficient. This
abstract data type is very expressive and permits the construction of very complex and
powerful rules. There is a third form in which rules may be expressed. A rule AST is
converted into an equivalent form suitable for storage in the Knowledge-base. The way in
which this information appears in the Knowledge-base depends on the storage technology.
Relational databases provide an especially convenient and efficient means for storing
metadata. The metadata corresponding to an AST in this case would reside in a collection of
tables. The specific scheme chosen for saving the metadata must permit the ASTs to be
rapidly reconstructed using database queries.
The diagram in Figure 3 summarizes the several conversion operations the Rule Translator
must perform as it adds rules to the Knowledge-base and as it retrieves rules from the
Knowledge-base for execution.
(a-b) / [x*(c-d)] ,
that might form some part of a rule. In the AST representation, this portion of the rule would
be expressed as a binary tree, like the one in Figure 4, whose nodes are either arithmetic
operators or operands.
Once created, AST representations are converted into rule metadata and stored in the
Knowledge-base. Rule metadata is simply a compact representation of ASTs. The role of the
Rule Translator in the rule editing process is illustrated in the data flow diagram of Figure 5.
In translating rules from one form to another, the structure of the original rule is never lost. It
is always possible to recreate a human-readable rule, exactly, from its Knowledge-base
representation or from its AST representation.
The Rule Engine (often referred to as an inference engine in AI literature) is responsible for
executing Knowledge-base rules. It retrieves rules from the Knowledge-base, converts them
to ASTs, and then provides them to its rule interpreter for execution. The Rule Engine
interpreter traverses the AST, executing actions specified in the rule along the way. This
process is depicted in Figure 6.
4.5 Rule Object Classes
The shell component, Rule Object Classes, is a container for object classes supporting,
Rule editing;
AST construction;
Conversion of ASTs to rule metadata;
Conversion of rule metadata to ASTs; and
Knowledge-base operations (query, update, insert, delete).
Q-4(b)Explain NLP
A Closure View:
Graph
SOLVED markings
AO* Algorithm:
4. Let S := {n}.
5. Until S = f do :
4. End.
6. End.
The nearest neighbour algorithm was one of the first algorithms used to determine a solution to the travelling
salesman problem. It quickly yields a short tour, but usually not the optimal one.
The nearest neighbour algorithm is easy to implement and executes quickly, but it can sometimes miss shorter
routes which are easily noticed with human insight, due to its "greedy" nature. As a general guide, if the last few
stages of the tour are comparable in length to the first stages, then the tour is reasonable; if they are much
greater, then it is likely that there are much better tours. Another check is to use an algorithm such as the lower
bound algorithm to estimate if this tour is good enough.
In the worst case, the algorithm results in a tour that is much longer than the optimal tour. To be precise, for
every constant r there is an instance of the traveling salesman problem such that the length of the tour length
computed by the nearest neighbour algorithm is greater than r times the length of the optimal tour. Moreover,
for each number of cities there is an assignment of distances between the cities for which the nearest neighbor
heuristic produces the unique worst possible tour
This simple type of network is interesting because the hidden units are free to construct their own
representations of the input. The weights between the input and hidden units determine when each hidden
unit is active, and so by modifying these weights, a hidden unit can choose what it represents
We also distinguish single-layer and multi-layer architectures. The single-layer organisation, in which all
units are connected to one another, constitutes the most general case and is of more potential computational
power than hierarchically structured multi-layer organisations. In multi-layer networks, units are often
numbered by layer, instead of following a global numbering.
1.4 Perceptrons
The most influential work on neural nets in the 60's went under the heading of 'perceptrons' a term
coined by Frank Rosenblatt. The perceptron (figure 4.4) turns out to be an MCP model ( neuron
with weighted inputs ) with some additional, fixed, pre--processing. Units labelled A1, A2, Aj ,Ap
are called association units and their task is to extract specific, localised featured from the input
images. Perceptrons mimic the basic idea behind the mammalian visual system. They were mainly
used in pattern recognition even though their capabilities extended a lot more.
Figure 1.4
C. Explain fuzzy set and crisp set. Mention application of fuzzy logic.
Ans.
Fuzzy set:
A fuzzy set is a pair (A,m) where A is a set and .
For each , m(x) is called the grade of membership of x in (A,m). For a finite set A =
{x1,...,xn}, the fuzzy set (A,m) is often denoted by {m(x1) / x1,...,m(xn) / xn}.
Let . Then x is called not included in the fuzzy set (A,m) if m(x) = 0, x is called fully
included if m(x) = 1, and x is called fuzzy member if 0 <m(x) < 1.[4] The set
is called the support of (A,m) and the set
is called its kernel.
Sometimes, more general variants of the notion of fuzzy set are used, with membership
functions taking values in a (fixed or variable) algebra or structureL of a given kind; usually it is
required that L be at least a poset or lattice
Crisp set:
Application of fuzzy logic: There are countless applications for fuzzy logic. In fact, some claim that
fuzzy logic is the encompassing theory over all types of logic. The items in this list are more common
applications that one may encounter in everyday life.
Bus Time Tables
How accurately do the schedules predict the actual travel time on the bus?
Bus schedules are formulated on information that does not remain constant. They use fuzzy logic
because it is impossible to give an exact answer to when the bus will be at a certain stop. Many
unforseen incidents can occur. There can be accidents, abnormal traffic backups, or the bus could break
down. An observant scheduler would take all these possibilities into account, and include them in a
formula for figuring out the approximate schedule. It is that formula which imposes the fuzziness
Temperature control (heating/cooling)
The trick in temperature control is to keep the room at the same temperature consistently. Well, that
seems pretty easy, right? But how much does a room have to cool off before the heat kicks in again?
There must be some standard, so the heat (or air conditioning) isn't in a constant state of turning on and
off. Therein lies the fuzzy logic. The set is determined by what the temperature is actually set to.
Membership in that set weakens as the room temperature varies from the set temperature. Once
membership weakens to a certain point, temperature control kicks in to get the room back to the
temperature it should be.
Medical diagnoses
How many of what kinds of symptoms will yield a diagnosis? How often are doctors in error?
Surely everyone has seen those lists of symptoms for a horrible disease that say "if you have at least 5
of these symptoms, you are at risk". It is a hypochondriac's haven. The question is, how do doctors go
from that list of symptoms to a diagnosis? Fuzzy logic. There is no guaranteed system to reach a
diagnosis. If there were, we wouldn't hear about cases of medical misdiagnosis. The diagnosis can only
be some degree within the fuzzy set.
Predicting travel time
This is especially difficult for driving, since there are plenty of traffic situations that can occur to slow
down travel.
As with bus timetabling, predicting ETA's is a great exercise in fuzzy logic. That's why it is called an
estimated time of arrival. A major player in predicting travel time is previous experience. It took me six
hours to drive to Philadelphia last time, so it should take me about that amount of time when I make the
trip again. Unfortunately, other factors are not typically considered. Weather, traffic, construction,
accidents should all be added into the fuzzy equation to deliver a true estimate.
Antilock Braking System
It's probably something you hardly think about when you're slamming on the brakes in your car
The point of an ABS is to monitor the braking system on the vehicle and release the brakes just before
the wheels lock. A computer is involved in determining when the best time to do this is. Two main
factors that go into determining this are the speed of the car when the brakes are applied, and how fast
the brakes are depressed. Usually, the times you want the ABS to really work are when you're driving
fast and slam on the brakes. There is, of course, a margin for error. It is the job of the ABS to be
"smart" enough to never allow the error go past the point when the wheels will lock
D. Explain cut predicate in detail.
Ans.
Prolog provides a predicate that performs this function. It is called the cut/1, represented by an
exclamation point (!).
The cut/1 effectively tells Prolog to freeze all the decisions made so far in this predicate. That is, if
required to backtrack, it will automatically fail without trying other alternatives. We will first examine
the effects of the cut/1 and then look at some practical reasons to use it . When the cut/1 is encountered,
it re-routes backtracking. It short-circuits backtracking in the goals to its left on its level, and in the
level above, which contained the cut/1. That is, both the parent goal and the goals of the particular rule
being execut/1ed are affected by the cut/1. The effect is undone if a new route is taken into the parent
goal.
We will write some simple predicates that illustrate the behavior of the cut/1, first adding some data to
backtrack over.
data(pentiumIII)
data(athlon).
Here is the first test case. It has no cut/1 and will be used for comparison purposes.
compare_cut_1(X) :-
data(X).
compare_cut_1('last chip').
This is the control case, which exhibits the normal behavior.
?- compare_cut_1(X), write(X), nl, fail.
pentiumIII
Athlon
last chip
no
Next, we put a cut/1 at the end of the first clause.
compare_cut_2(X) :-
data(X),
!.
compare_cut_2('last chip').
Note that it stops backtracking through both the data subgoal (left), and the compare_cut_2/1 parent
(above).
?- compare_cut_2(X), write(X), nl, fail.
pentiumIII
no
Next we put a cut/1 in the middle of two subgoals.
compare_cut_3(X,Y) :-
data(X),
!,
data(Y).
compare_cut_3('last chip').
Note that the cut inhibits backtracking in the parent compare_cut_3/2 and in the goals to the left of
before) the cut (first data). The second data/1 to the right of (after) the cut is still free to backtrack.
?- compare_cut_3(X,Y), write(X-Y), nl, fail.
pentiumIIIpentiumIII
pentiumIIIAthlon
no
Performance is the main reason to use the cut/1. This separates the logical purists from the pragmatists.
Various arguments can also be made as to its effect on code readability and maintainability. It is often
called the 'goto' of logic programming. You will most often use the cut/1 when you know that at a
certain point in a given predicate, Prolog has either found the only answer, or if it hasn't, there is no
answer. In this case you insert a cut/1 in the predicate at that point. Similarly, you will use it when you
want to force a predicate to fail in a certain situation, and you don't want it to look any further.
E. Explain properties of good knowledge representation system.
Ans.
The following properties should be possessed by a knowledge representation system.
Representational Adequacy
Ans.
When one writes a Prolog program, usually the facts and rules of the program are stored in a (text) file,
and then loaded into the Prolog interpreter. Files have other uses in Prolog, too.
For example, we may wish to write out a table of results that have been computed for us by our Prolog
program. One can use built-in predicates like write, nl, putc, tab and others to write out the table, but by
default it will appear on the computer screen. To direct this output to a file, we use the tell built-in
predicate. Suppose that we wish to write the table to a file called "mytable.data". By executing the
(pseudo-)goal tell("mytable.data"), we tell Prolog that the new current output stream is to be the file
"mytable.data". Subsequent writes will go to this file. When one wishes to stop writing to the file and
resume writing on the screen, one uses the built-in predicate told (with no arguments). Also, the query
?- telling(X).bindsX to the name of the current output file. If the current output stream is not a file, then
X will be bound to something that indicates that the current output stream is the screen - for example,
in Unix, X may be bound to the atom stdout (standard output, which is normally the screen). Example:
The built-in Prolog predicate append/1 is like tell, except that it arranges for subsequent write
operations to add data to the end of the specified file, rather than overwriting the file with the first
subsequent write operation. If myothertable.data initially contains, say, a single line, This is the first
line, then append/1 works as follows:
The situation for reading from a file is analogous to writing (except that there is no analogue for
append/1). One can use built-in predicates like read, getc and others to read, by default from the
keyboard. By executing the (pseudo-)goal see('mydata.text'), we tell Prolog that the new current input
stream is to be the file mydata.text. Subsequent reads will come from this file. When one wishes to stop
reading from the file and resume reading from the keyboard, one uses the built-in predicate seen (with
no arguments). Also, the query ?- seeing(X).bindsX to the name of the current input file. If the current
input stream is not a file, then X will be bound to something that indicates that the current output
stream is the screen - for example, in Unix, X may be bound to the atom stdin (standard input, which is
normally the keyboard). Example:
What happens if you try to read from a file and there is nothing (left) to read, either because the file is
empty, or you have previously read everything there was to read in this file? In this case, Prolog binds
the variable that was the argument to read to the special atom end_of_file. Knowing this means that
you can test after a read to make sure that you did not hit end of file. Example:
?- see('empty.dat'), read(Term).
Term = end_of_file
Backtracking is a general algorithm for finding all (or some) solutions to some computational problem, that
incrementally builds candidates to the solutions, and abandons each partial candidate c ("backtracks") as soon as
it determines that c cannot possibly be completed to a valid solution.
Example:Constraint satisfaction
The general constraint satisfaction problem consists in finding a list of integers x = (x[1],x[2], , x[n]), each in
some range {1, 2, , m}, that satisfies some arbitrary constraint (boolean function) F.
For this class of problems, the instance data P would be the integersm and n, and the predicate F. In a typical
backtracking solution to this problem, one could define a partial candidate as a list of integers c = (c[1],c[2],
c[k]), for any k between 0 and n, that are to be assigned to the first k variables x[1],x[2], , x[k]). The root
candidate would then be the empty list (). The first and next procedures would then be
functionfirst(P,c)
k length(c)
ifk = n
thenreturn
elsereturn (c[1], c[2], , c[k], 1)
functionnext(P,s)
k length(s)
ifs[k] = m
thenreturn
elsereturn (s[1], s[2], , s[k-1], 1 + s[k])
For example, if F is the conjunction of several boolean predicates, F = F[1] F[2] F[p], and each F[i]
depends only on a small subset of the variables x[1], , x[n], then the reject procedure could simply check the
terms F[i] that depend only on variables x[1], , x[k], and return trueif any of those terms returns false. In fact,
reject needs only check those terms that do depend on x[k], since the terms that depend only on x[1], , x[k-1]
will have been tested further up in the search tree.
Assuming that reject is implemented as above, then accept(P,c) needs only check whether c is complete, that is,
whether it has n elements.
It is generally better to order the list of variables so that it begins with the most critical ones (i.e. the ones with
fewest value options, or which have a greater impact on subsequent choices).
One could also allow the next function to choose which variable should be assigned when extending a partial
candidate, based on the values of the variables already assigned by it. Further improvements can be obtained by
the technique of constraint propagation.
In addition to retaining minimal recovery values used in backing up, backtracking implementations commonly
keep a variable trail, to record value change history. An efficient implementation will avoid creating a variable
trail entry between two successive changes when there is no choice point, as the backtracking will erase all of
the changes as a single operation.
An alternative to the variable trail is to keep a timestamp of when the last change was made to the variable. The
timestamp is compared to the timestamp of a choice point. If the choice point has an associated time later than
that of the variable, it is unnecessary to revert the variable when the choice point is backtracked, as it was
changed before the choice point occurred.
Or
Que.5
domains
integerlist=integer*
predicates
inter_union(integerlist,integerlist)
intersect(integerlist,integerlist,integerlist)
union(integerlist,integerlist,integerlist)
delete(integer,integerlist,integerlist)
member(integer,integerlist)
clauses
inter_union(L1,L2):-
write("Intersection\n"),
intersect(L1,L2,L4),
write(L4),
write("\n Union\n"),
union(L1,L2,L4),
write(L4),
nl.
intersect([H|Tail1],L2,[H|Tail3]):-
member(H,L2),
intersect(Tail1,L2,Tail3).
intersect([H|Tail1],L2,Tail3):-
not(member(H,L2)),
intersect(Tail1,L2,Tail3).
intersect([],_,[]).
member(X,[X|_]).
member(X,[Head|Tail]):-
not(X=Head),
member(X,Tail).
union([],L,L).
union([H|Tail1],L2,[H|Tail3]):-
member(H,L2),
delete(H,L2,L3),
union(Tail1,L3,Tail3).
union([H|Tail1],L2,[H|Tail3]):-
not(member(H,L2)),
union(Tail1,L2,Tail3).
delete(X,[X|Tail],Tail):-
!.
delete(X,[Y|Tail],[Y|Z]):-
delete(X,Tail,Z).
domains
list=integer*
predicates
seln_sort(list,list)
minimum(list,integer,integer)
efface(list,integer,list)
clauses
seln_sort([X|Xs],[Y|Ys]):-minimum(Xs,X,Y),efface([X|Xs],Y,Zs),seln_sort(Zs,Ys).
seln_sort([],[]).
minimum([Y|Ys],X,Z):-Y<=X,!,minimum(Ys,Y,Z).
minimum([_|Ys],X,Z):-minimum(Ys,X,Z).
minimum([],X,X).
efface([Y|Xs],Y,Xs):-!.
efface([X|Xs],Y,[X|Zs]):-efface(Xs,Y,Zs).
Goal :seln_sort([1,3,45,5,14,3]X).