B219 Intelligent Systems Prolog Programming -...

24
B219 Intelligent Systems Week 9 Lecture Notes page 1 of 1 Prolog Programming - Input/Output in Prolog write(term) and read(term) § Predicate write(term) causes a term to be written to the current output stream (the monitor screen by default) § If term is uninstantiated, an underscore followed by a number unique to the variable will be output, eg, _64 § Predicate read(term) is used to read a term from the current input stream (the keyboard by default) Input can be redirected using predicates see(filename) to open a file for input, and seen to close file and read from keyboard again Output can be redirected using predicates tell(filename) to open a file for output, and told to close file and write to the keyboard again

Transcript of B219 Intelligent Systems Prolog Programming -...

B219 Intelligent Systems

Week 9 Lecture Notes page 1 of 1

Prolog Programming - Input/Output in Prolog

write(term) and read(term)

§ Predicate write(term) causes a term to be written to the current output stream (the monitor screen by default)

§ If term is uninstantiated, an underscore followed by a number unique to the variable will be output, eg, _64

§ Predicate read(term) is used to read a term from the current input stream (the keyboard by default)

Input can be redirected using predicates

see(filename) to open a file for input, and

seen to close file and read from keyboard again

Output can be redirected using predicates

tell(filename) to open a file for output, and

told to close file and write to the keyboard again

B219 Intelligent Systems

Week 9 Lecture Notes page 2 of 2

I/O in Prolog - Example:

/* The following program contains a database of positions and employees in a company. It specifies the position of an employee, given the name */

position(‘Spielberg’, director).

position(‘Allen’, manager).

position(‘Lee’, supervisor).

find_position:-

write(‘Whose position do you wish to know?’),

read(Input), position(Input, Output),

write(‘The position of ‘), write(Input),

write(‘ is ‘), write(Output), write(‘.’).

?- find_position.

Whose position do you wish to know?

‘Spielberg’.

The position of Spielberg is director

B219 Intelligent Systems

Week 9 Lecture Notes page 3 of 3

List application - Sorting

Insertion sort algorithm is based on the following: If all items in a list of size N-1 are already sorted, then we insert the Nth item in the list by searching along the list and finding the correct location.

We assume the sorting is to be in ascending order. The main part of the algorithm can now be expressed in Prolog: isort([],[]). isort([X|Tail],SList):- isort(Tail,STail), insert(X,STail,SList). The isort predicate strips off the head of the list, sorts the tail recursively, then finally inserts the head item (X) into the correct location. The recursion stops when the list to be sorted become empty. We must now define the insert predicate.

B219 Intelligent Systems

Week 9 Lecture Notes page 4 of 4

The insert predicate Compares the value of the item to be inserted with the head of the list. If it is less than this value, then the new item must be inserted just before this head, otherwise the item is inserted into the new tail. insert(X,[],[X]). insert(X,[H|Tail],[X,H|Tail]):- X =< H. insert(X,[H|Tail],[H|NewTail]):- X > H, insert(X,Tail,NewTail). The first clause terminates the search process when the item (X) is to be inserted into an empty list, it creates a new list with a single item (X) in it. The second clause is where the value of X is less than, or equal to, the value of the head (H). In this case the new list is created by adding X to the front of the list with the construct [X,H|Tail]. The final clause matches for the case when the item (X) is greater than the head of the list (H). In this case the item is inserted into the current Tail.

B219 Intelligent Systems

Week 9 Lecture Notes page 5 of 5

We now have a complete program which can be used as follows: ?- isort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1], S) S = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

B219 Intelligent Systems

Week 9 Lecture Notes page 6 of 6

A program to change a sentence into another

A program that responds with an altered version of an input sentence, eg,

You: you are a computer

Prolog: i am not a computer

You: do you speak french

Prolog: no i speak german

Steps involved:

- Change each you to i

- Change are to am not

- Change french to german

- Change do to no

We can represent a sentence as a list of words

[like, this, sentence]

and define a predicate alter(X,Y) to alter sentence X into sentence Y

B219 Intelligent Systems

Week 9 Lecture Notes page 7 of 7

Predicate alter

?- alter([do you know french], Y].

Y = [no i know german]

Main functions:

• change head of input list into another word, let this word become head of output list

• alter tail of input list and let it become the tail of output list

• if we have reached the end of the input list, then terminate the output list with an empty list [ ]

Summarising in Prolog terminology:

altering a list with head H and tail T gives a list with head X and tail Y if changing word H gives word X, and altering list T gives list Y.

alter([], []).

alter([H|T], [X|Y]) :- change(H,X), alter(T,Y).

B219 Intelligent Systems

Week 9 Lecture Notes page 8 of 8

Defining change

change(X,Y) means word X is to be changed into word Y

change(you, i).

change(are, [am, not]).

change(french, german).

change(do, no).

/* if there is no match, don’t change */

change(X, X)

B219 Intelligent Systems

Week 9 Lecture Notes page 9 of 9

Getting more out of predicates Joining two lists (Concatenating/Appending)

append( L1, L2, L3) where L3 = L1 + L2, eg, ? - append([a,b], [c,d], NewList). NewList = [a,b,c,d] Two cases

1. First argument an empty list append( [ ], L, L)

2. First argument has a head and a tail

append( [ X | L1], L2, [X | L3] ) :- append( L1, L2, L3).

[X | L1] X L1 L2 L3 X L3

[X | L3]

B219 Intelligent Systems

Week 9 Lecture Notes page 10 of 10

?- append([a,b], [c,d], Newlist).

Newlist = [a,b,c,d]

Predicate append can be used in a different way -

/* Which list, when appended to list [a], gives list [a,b,c] */

?- append([a], X, [a,b,c]).

X = [b,c]

/* What are the different ways list [a,b,c] can be decomposed? */

?- append(X, Y, [a,b,c]).

X = []

Y = [a,b,c]

More (y/n)? y

X = [a]

Y = [b,c]

B219 Intelligent Systems

Week 9 Lecture Notes page 11 of 11

More (y/n)? y

X = [a,b]

Y = [c]

More (y/n)? y

X = [a,b,c]

Y = []

Predicate myinsert

/* Inserts item X at position P in list L to give list NewList */

myinsert(X, P, L, Newlist)

myinsert can be used to implement a predicate mydelete to delete an item at position P

mydelete(P, L, List)

Eg,

?- mydelete(2,[a,b,c,d],X).

X = [a,b,d]

B219 Intelligent Systems

Week 9 Lecture Notes page 12 of 12

MORE ON RECURSION

Example 2 : A simple family tree.

peter (margaret)

john (barbara)

carolandrew (rachel)

sally

trevor nicholas

christine (frank)

jennifer (simon)

sarah (david)

B219 Intelligent Systems

Week 9 Lecture Notes page 13 of 13

We can represent the information contained in the family tree via two predicates married(X,Y) and child_of(X,Y).

Thus our prolog database would contain facts of the following form

married(peter,margaret).

married(john,barbara).

child_of(john,peter).

child_of(christine,peter).

child_of(jennifer,peter).

child_of(john,margaret).

child_of(christine,margaret).

child_of(jennifer,margaret). . . etc.

B219 Intelligent Systems

Week 9 Lecture Notes page 14 of 14

SOME SIMPLE PREDICATES

parent_of(X,Y) :- child_of(Y,X).

grandchild_of(X,Y) :- child_of(X,A) , child_of(A,Y).

siblings(X,Y) :- child_of(X,A) , child_of(Y,A) , not(X = Y).

sister_of(X,Y) :- siblings(X,Y) , female(X).

brother_of(X,Y) :- siblings(X,Y) , male(X).

B219 Intelligent Systems

Week 9 Lecture Notes page 15 of 15

Consider the query:

Is nicholas a descendent of peter ?

A descendent is anyone that is a child, grandchild, great-grandchild, great-great-grandchild, ... , and so on.

How might we define a general predicate

descendent_of(X,Y) ?

We make use of the following simple observation

X is a descendent of Y if one of X's parents is also a descendent of Y.

This translates directly into the (recursive) Prolog clause

descendent_of(X,Y) :- child_of(X,A) , descendent_of(A,Y).

B219 Intelligent Systems

Week 9 Lecture Notes page 16 of 16

What is the appropriate TERMINATING CONDITION ?

The recursion stops when we reach a direct descendent.

Our final definition is thus

descendent_of(X,Y) :- child_of(X,Y).

descendent_of(X,Y) :- child_of(X,A) , descendent_of(A,Y).

B219 Intelligent Systems

Week 9 Lecture Notes page 17 of 17

Searching Problems are solved by searching among alternative choices Examples:

- Find a route to get to the city from Murdoch (the freeway is closed!) - Decide on the next move in a game of chess

Typically, we have an initial scenario (state) and a goal (solution state) We consider a number of alternative steps (strategies) and select one This process is repeated until (hopefully) the solution is arrived at In AI, this aspect of intelligent behaviour is known as problem solving by state space search

B219 Intelligent Systems

Week 9 Lecture Notes page 18 of 18

Problem Solving by State Space Search The states in a problem domain consist of the initial state, the goal state and all possible intermediate states Together, they form the state space for a particular problem Examples: In a game of chess, each legal configuration of the board is a state and the players move around in the state space Success in solving a problem depends on coming up with an appropriate representation scheme for the states

B219 Intelligent Systems

Week 9 Lecture Notes page 19 of 19

State space graph In computer science, a graph is a collection of nodes connected by links (arcs) Graphs are used to represent state spaces for problem solving Consider the game of noughts and crosses Given any board situation (configuration), a player can only make a finite number of moves

B219 Intelligent Systems

Week 9 Lecture Notes page 20 of 20

Starting with an empty board, each board configuration can be represented as a node The links of the graph represent legal moves from one board configuration to another These nodes thus correspond to different states of the game board - known as a state space graph Think of a representation scheme (a data structure) for this state space How many nodes will the state space graph consist of? (answers at the end of lecture notes)

B219 Intelligent Systems

Week 9 Lecture Notes page 21 of 21

As another example, consider diagnosing a mechanical fault in a car It is possible to construct a state-space graph for this more complicated problem Let each node represent a state of partial knowledge about the car’s mechanical problems The process of examining the symptoms of the fault and inducing its cause may be thought of as searching through states of increasing knowledge A problem solver can diagnose car trouble by searching for a path through this graph that is consistent with the symptoms of a particular defective car State space search may be used to approach practically any problem

B219 Intelligent Systems

Week 9 Lecture Notes page 22 of 22

How intelligent is searching? Search provides a framework for automating problem solving Simple exhaustive search of a large space is impractical It fails to capture the substance of intelligent activity Humans do not use exhaustive search Eg, The chess player only examines moves that experience has shown to be effective The doctor does not require tests that are not somehow indicated by the symptoms at hand Human problem solving seems to be based on some judgemental rules

B219 Intelligent Systems

Week 9 Lecture Notes page 23 of 23

Heuristics - “rules of thumb” Rules based on experience often guide our search to those portions of the state space that somehow seem promising These are known as heuristics (rules of thumb). heuristics comes from heuriskein (Greek - to discover) A heuristic is a strategy for selectively searching a problem space or reducing the size of the problem space What common heristics can you think of in a game of noughts and crosses? heuristics are not fool-proof - but should be effective “most of the time” The greatest contribution of AI in problem solving is the introduction of heristics in searching State space search gives us a means of formalising the problem-solving process Heuristics allow us to infuse that formalism with intelligence

B219 Intelligent Systems

Week 9 Lecture Notes page 24 of 24

Putting things in perspective - So far we’ve been introduced to predicate calculus and Prolog. They provide a means of describing objects and relations in a problem domain Inference rule modus ponens

P →→ Q P

---------- Q

allows us to infer new knowledge from these descriptions. These inferences define a space that is searched to find a problem solution