33
TCP1211-Logic Programming Control and Side Control and Side Effects Effects Programming Programming Faculty of Information Technology Multimedia University

TCP1211-Logic Programming Control and Side Effects Programming Faculty of Information Technology Multimedia University

Embed Size (px)

Citation preview

TCP1211-Logic Programming

Control and Side Control and Side Effects Effects

ProgrammingProgrammingFaculty of Information Technology

Multimedia University

TCP1211-Logic Programming

OutlineOutline

Performing Input and Output operations.Performing Input and Output operations. Equality and Comparison operators.Equality and Comparison operators. Defining new operators.Defining new operators.

TCP1211-Logic Programming

Input and Output Input and Output Streams (1)Streams (1)

Input StreamsFile1

File2

User...

Prolog Engine

Filex

Filey

User...

OutputStreams

The user input stream is the default input to Prolog system.User terminal (keyboard) is a user input stream where the user key in data.

The user output stream is the default output to Prolog system.User terminal (screen) is a user output stream where the user can see the results (which are not saved).

TCP1211-Logic Programming

Input and Output Input and Output Streams (2)Streams (2)

Input StreamsFile1

File2

User...

Prolog Engine

Filex

Filey

User...

OutputStreams

We can always change the current input/output streams

Input StreamsFileFile11

File2

User...

Prolog Engine

FileFilexx

Filey

User...

OutputStreams

TCP1211-Logic Programming

Input and Output Streams Input and Output Streams (3)(3)

At the beginning of the execution, the input stream and output stream correspond to the user terminals(keyboard and screen).

The goal: see(FileName). causes the input to be switched from the previous input stream to FileName.Therefore, Prolog is ready to read the input from FileName.

too_easy(prolog).boring(X):-too_easy(X)....

?- see(‘kb1.pl’).yes.

?- read(X).X = too_easy(prolog)

?- see(user).yes.

kb1.pl

TCP1211-Logic Programming

Input and Output Streams Input and Output Streams (4)(4)

The goal: tell(FileName). causes the output to be switchedto FileName instead of the previous output stream. Therefore, Prolog is ready to display the output to FileName.

likes(ali, garfield).

?- tell(‘kb2.pl’).yes.?- write(‘likes(ali, garfield).’).yes.?- tell(user).yes.

kb2.pl

TCP1211-Logic Programming

Processing Files of Terms – Processing Files of Terms – Reading Terms (1)Reading Terms (1)

To Read a Term:

read(X): a predefined predicate that read a term X from user input stream (keyboard or from a file).

Assume the input/output streams are user.

?- read(P).?- read(P).:12.P = 12

inputoutput

?- read(Y).?- read(Y).:male(peter).Y = male(peter)

TCP1211-Logic Programming

Processing Files ofTerms – Processing Files ofTerms – Reading Terms (2)Reading Terms (2)

Assume the input stream is the file Kb1.pl whereas the output stream is user (screen)

female(sarah).smart(sarah).13.person(X):-female(X).

?- see(’C:\Program Files\WIN-PROLOG 4\Kb1.pl’).yes?- read(P).P = female(sarah)?- read(P).P = smart(sarah)?- read(P).P = 13?- read(P).P = (person(_46718) :- female(_46718))?- read(P).P = end_of_file?- seen.yes

Kb1.plUser Streams

TCP1211-Logic Programming

Processing Files of Terms – Processing Files of Terms – Writing Terms (1)Writing Terms (1)

To Write a Term

write(X): a predefined predicate that output a term X to the output stream from user input stream (keyboard or from a file).

Assume the output stream is user.

dispList([]).dispList([H|T]):- write(H), tab(3), dispList(T).

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

yes

TCP1211-Logic Programming

Processing Files ofTerms – Processing Files ofTerms – Writing Terms (2)Writing Terms (2)

female(sarah).smart(sarah).13.person(X):-female(X). ?- tell(’C:\Program Files\WIN-PROLOG 4\Kb1.pl’).

yes?- write (male(pet)).yes?- write (person(sam)).yes?- told.yes

female(sarah).smart(sarah).13.person(X):-female(X).male(pet)person(sam)

Assume the input stream is the file Kb1.pl whereas the output stream is user (screen).

Kb1.pl

Kb1.pl

TCP1211-Logic Programming

Processing CharactersProcessing Characters

put(X)put(X):: X must be an ASCII code, the corresponding characteris written on the current output stream.

Eg.?- put(65).A

get0(Y)get0(Y):: read a single character from the current input stream.Y will be instantiated with the ASCII code of the character.

Eg.?-get0(X).DX = 68 (ASCII CODE of ‘D’)

TCP1211-Logic Programming

Updating clauses of the Updating clauses of the Knowledge Base (1)Knowledge Base (1)

assertassert(C): asserts (add) a clause C at the end of the KB.

assertassertaa(C): asserts (add) a clause C at the beginning of the KB.

assertassertzz(C): asserts (add) a clause C at the end of the KB.

retractretract(C): deletes a clause that matches the clause C.

TCP1211-Logic Programming

Updating clauses of the Updating clauses of the Knowledge Base (2)Knowledge Base (2)

?- assert(good(peter)).yes

?- good(X).X = peter

?- retract(good(peter)).yes

?- good(X).no

TCP1211-Logic Programming

Testing the types of Testing the types of termsterms

varvar(X): succeeds if X is currently an uninstantiated variable.

nonvarnonvar(X): succeeds if X is not a variable or

is already an instantiated variable.

atomatom(X): succeeds if X is currently an atom.

integerinteger(X): succeeds if X is currently an integer.

floatfloat(X): succeeds if X is currently a real number.

numbernumber(X): succeeds if X is currently a number.

atomicatomic(X): succeeds if X is currently an atom or a number.

compoundcompound(X): succeeds if X is currently a structure.

TCP1211-Logic Programming

Testing the types of terms – Testing the types of terms – Example Example

Count how many times an atom is in a given list L :

count(Input,[],0).count(Input, [H|Tail], N):-count(Input,Tail,N).count(Input, [Input|T],N):- atom(Input), count(Input,T,N1),

N is N1+1.

TCP1211-Logic Programming

Equality ComparisonEquality Comparison“=” X = Y is true if X and Y match.“is” X is E: where E is an arithmetic expression. Is true if the evaluated expression matches with X

?- L = [a,b,c].L = [a,b,c]

?- X = Y.X=Y= _

?- X = peter.X = peter

?- peter=X.X = peter

?- peter=pet.no

?- X = 3+2.X = 3 + 2

?- X is 3+2.X = 5

?- X =3+2, Y is X.X = 3 + 2 ,Y = 5

TCP1211-Logic Programming

(In)Equality“=:=” E1 =:=E2 is true if E1 is equal with E2.“=\=” E1 =:=E2 is true if E1 is not equal to E2.

?- 2 is X. Error !!!!!!!

?- Y is X. Error!!!!!!!!

?- 2+3 =:= 3+2.yes

?- X = 4, Y is X+1, Y=:=X.no

?- 2+3 =:= 12-7.yes

?- X = 4, Y is X+1, Y=\=X. X = 4 ,Y = 5

?- X+2=:=X+2. Error !!!!!

TCP1211-Logic Programming

“= =” Literal equality“\= =” Literal Inequality

Term1 = = Term2 is true if Term1 is literally identical to Term2Term1 \= = Term2 is true if Term1 is literally different from Term2

?- X+2 ==X+2.X = _?- 2 ==2.Yes?- peter ==peter.yes?- X == X.X = _?- faster(ali, ahmad)==faster(ali, ahmad).yes

?- faster(ali, ahmad)==faster(ali, X).No

?- X\= =Y.yes

TCP1211-Logic Programming

Defining our own Defining our own operatorsoperators

op( Precedence, Type, Functor).

Functor: operator name.Precedence: integer from 1 to 1200.

The lower the number the higher is the precedenceType: Prefix/infix/postfix format of the operator.

TCP1211-Logic Programming

Operator Precedence – Operator Precedence – Example 1Example 1

P A B.

The built in operator :- has Precedence 1200 and Type xfxThe built in operator , has Precedence 1000and Type xfy

is of higher priority. This means we execute A B first and then we execute

,

, ,:-

:-

TCP1211-Logic Programming

Prefix/Infix/Postfix Prefix/Infix/Postfix operators (1) operators (1)

Infix format: 3+2-5/2 : arg1 Op arg2 ….The operator is Inside the expression

Prefix format: +(3, -(2, /(5,2)) ) : Op (arg1, Op (arg2, ….))The operator Precedes the arguments

Postfix format: (3,(2, (5,2)/)-)+ : (arg1, (arg2…)Op2)Op1The arguments Precede the operator

TCP1211-Logic Programming

Prefix/Infix/Postfix Prefix/Infix/Postfix operators (2)operators (2)

Infix format: xfx nonassociative / xfy right-assoc / yfx left-assoc

Prefix format: fx nonassociative / fy right-assoc

Postfix format: xf nonassociative / yf left-assoc

TCP1211-Logic Programming

Left and Right Left and Right AssociativeAssociative

10+5+8 is executed as (10+5) + 8 and not as 10+(5+8)because + “yfx” left-associative.

4^3^2 is executed as 4^(3^2) and not (4^3)^2 because ^ “xfy” right-associative.

TCP1211-Logic Programming

:- op(1000, xfy, isa).:- op(900, xfx, of).:- op(800, xfy, and).

A and B :- A,B.

‘Ali’ isa lecturer of tcp1211 and tcp1241.‘Ali’ isa sportsman.

?- 'Ali' isa Somebody.Somebody = (lecturer of tcp1211 and tcp1241) ;Somebody = sportsman

?- 'Ali' isa lecturer of SomeSubjects.SomeSubjects = (tcp1211 and tcp1241)

Defining operators – Defining operators – Example 1Example 1

TCP1211-Logic Programming

?- Who isa Somebody.Who = 'Ali' ,Somebody = (lecturer of tcp1211 and tcp1241) ;Who = 'Ali' ,Somebody = sportsman

?- 'Ali' isa lecturer of tcp1211 and AnotherSubject.AnotherSubject = tcp1241

Defining operators – Defining operators – Example (2)Example (2)

TCP1211-Logic Programming

More about defining operatorsMore about defining operators

An operator definition do not specify its An operator definition do not specify its meaning.meaning.

An operator definition does not indicate when An operator definition does not indicate when a query involving the operator will evaluate to a query involving the operator will evaluate to true. true.

Any expression constructed using newly Any expression constructed using newly defined operators will be mapped to Prolog’s defined operators will be mapped to Prolog’s internal representation.internal representation.

Example: Consider the following operator Example: Consider the following operator definition –definition –

:-op(500, xf, is_smart). :-op(500, xf, is_smart).

TCP1211-Logic Programming

More about defining More about defining operators(cont.)operators(cont.)

This definition allows us to form the This definition allows us to form the following statement: following statement: john is_smart.john is_smart.

We can then issue the query We can then issue the query ?-john ?-john is_smart. is_smart.

In order to answer this query, Prolog will In order to answer this query, Prolog will try to prove try to prove is_smart(john). is_smart(john). which is which is Prolog’s internal representation.Prolog’s internal representation.

Thus, an operator definition tells Prolog Thus, an operator definition tells Prolog how to translate a user friendly notation how to translate a user friendly notation into its internal representation.into its internal representation.

TCP1211-Logic Programming

SummarySummary

How to specify and use input/output streams in How to specify and use input/output streams in Prolog.Prolog.

Some built-in predicates for testing the types Some built-in predicates for testing the types of terms.of terms.

The The difference difference between various equality between various equality comparison operators.comparison operators.

How to define your own operators - prefix, How to define your own operators - prefix, infix and postfix. infix and postfix.

TCP1211-Logic Programming

Prolog – Tip No. Prolog – Tip No. 11

TCP1211-Logic Programming

Variables – How different are they Variables – How different are they from C’s?from C’s?

Variables in Prolog are not typed.Variables in Prolog are not typed. Therefore, variable declarations are not Therefore, variable declarations are not

required.required. ProblemProblem: students accustomed to : students accustomed to

imperative languages feel reluctant to imperative languages feel reluctant to create new variables ‘on-the-fly’.create new variables ‘on-the-fly’.

This leads to incorrect codes This leads to incorrect codes described described next. next.

TCP1211-Logic Programming

Variables – assignment vs. Variables – assignment vs. instantiationinstantiation

Variables in Prolog cannot be assigned! Variables in Prolog cannot be assigned! The can only be instantiated.The can only be instantiated.

The value of a variable can only be The value of a variable can only be changed by un-instantiating it first.changed by un-instantiating it first.

Problem:Problem: The misconception that The misconception that instantiation and assignment are the instantiation and assignment are the same. same.

TCP1211-Logic Programming

Is this code correct?Is this code correct?

factorial(Number,factorial(Number,Factorial):-Factorial):-

NewNumber is Number-1,NewNumber is Number-1,

factorial(NewNumber,factorial(NewNumber,FactorialFactorial),),

Factorial Factorial is Number * is Number * Factorial.Factorial.

TCP1211-Logic Programming

Why does it fail to work?Why does it fail to work?

Due to the following clause:Due to the following clause:

Factorial Factorial is Number * is Number * Factorial.Factorial.

Why?Why?

How to avoid this? How to avoid this? Use new variables Use new variables (generously). Avoid reusing variables unless you (generously). Avoid reusing variables unless you are very sure that the reuse will give correct are very sure that the reuse will give correct behavior.behavior.