Intelligent systems Lection 5 Logic programming in Prolog.

Slides:



Advertisements
Similar presentations
Problem Solving Well-formed predicate calculus expressions provide a means of describing objects and relations in a problem domain and inference rule.
Advertisements

Prolog.
1 Introduction to Prolog References: – – Bratko, I., Prolog Programming.
Inference and Reasoning. Basic Idea Given a set of statements, does a new statement logically follow from this. For example If an animal has wings and.
1 Logic Programming. 2 A little bit of Prolog Objects and relations between objects Facts and rules. Upper case are variables. parent(pam, bob).parent(tom,bob).
Lecture 2: Systems Engineering
Programming in Visual Basic
CSC 423 ARTIFICIAL INTELLIGENCE
Introduction to C Programming
Chapter 12 - Logic Programming
CS 330 Programming Languages 12 / 12 / 2006 Instructor: Michael Eckmann.
For Friday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
Building Control Algorithms For State Space Search
Lecture 24 Farmer, Goat, Cabbage and Wolf Problem Continued 1 The “Russian Farmer” Problem Continued.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 2: Input, Processing, and Output
Introduction to C Programming
(9.1) COEN Logic Programming  Logic programming and predicate calculus  Prolog statements  Facts and rules  Matching  Subgoals and backtracking.
Prolog Programming Lecture Module 13. Objective ● What is Prolog? ● Prolog program ● Syntax of Prolog ● Prolog Control Strategy ● Execution of Prolog.
Formal Models of Computation Part II The Logic Model
AI/ES (Artificial Intelligence / Expert System) Visual Prolog: Part Fall. SME., Pukyong Nat ’ l Univ. Kim, Minsoo.
Input, Output, and Processing
Getting Started with Visual Prolog
For Wednesday Read “lectures” 7-10 of Learn Prolog Now Chapter 9, exs 4 and 6. –6 must be in Horn clause form Prolog Handout 2.
Introduction To PROLOG World view of imperative languages. World view of relational languages. A PROLOG program. Running a PROLOG program. A PROLOG.
Chapter 2 Syntax and meaning of Prolog Programs LP and Prolog Chapter 22 PROLOG domains variable name = type predicates relation(variable name,
Chapter 7 Turbo Prolog Chapter 7 Turbo Prolog Artificial Intelligence ดร. วิภาดา เวทย์ประสิทธิ์ ภาควิชาวิทยาการคอมพิวเตอร์ คณะ วิทยาศาสตร์ มหาวิทยาลัยสงขลานครินทร์
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
Programming, an introduction to Pascal
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Logic Programming CSC 358/ Outline Pattern matching Unification Logic programming.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
Logic Programming and Prolog Goal: use formalism of first-order logic Output described by logical formula (theorem) Input described by set of formulae.
1 Debugging and Syntax Errors in C++. 2 Debugging – a process of finding and fixing bugs (errors or mistakes) in a computer program.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
1 Natural Language Processing Chapter AI & ESChapter 6 NLP 2 NLP Language translation / multilingual translation Language understanding Figure.
Chapter Topics 2.1 Designing a Program 2.2 Output, Input, and Variables 2.3 Variable Assignment and Calculations 2.4 Variable Declarations and Data Types.
In The Name Of Allah Lab 03 1Tahani Aldweesh. objectives Searching for the solution’s. Declaration. Query. Comments. Prolog Concepts. Unification. Disjunction.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
For Friday No reading Prolog Handout 2. Homework.
07/10/04 AIPP Lecture 5: List Processing1 List Processing Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 5 07/10/04.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Bill Tucker Austin Community College COSC 1315
Numbers in ‘C’ Two general categories: Integers Floats
Prolog a declarative language
For Friday No reading Prolog handout 3 Chapter 9, exercises 9-11.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now:
CMPT 120 Topic: Python strings.
The Selection Structure
Chapter Topics 2.1 Designing a Program 2.2 Output, Input, and Variables 2.3 Variable Assignment and Calculations 2.4 Variable Declarations and Data Types.
Tests, Backtracking, and Recursion
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Variables and Arithmetic Operations
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
“The fastest I/O is no I/O.” Nils-Peter Nelson, Bell Labs
Topics Introduction to File Input and Output
Prolog a declarative language
Prolog a declarative language
Prolog a declarative language
Artificial Intelligence Problem solving by searching CSC 361
4. Computational Problem Solving
WEEK-2.
Chapter 2: Input, Processing, and Output
Topics Introduction to File Input and Output
EECE.2160 ECE Application Programming
Introduction to C Programming
Problem Solving by Searching Search Methods :
Presentation transcript:

Intelligent systems Lection 5 Logic programming in Prolog

Syntax of Prolog

:- implication or ←,conjunction ;disjunction.End of clause _name of variable, unused in later process of interpretation (anonimous variable) grandmother(X,Y) :- mother(X,Z), parent(Y,Z). Clause-rule mother(cathy, donald).Clause-fact

Solving of task in Prolog Solving of task in Prolog (or interpretation of program) is based on unification ( kind of backward inference). Unification began from predicate-goal, which is needed to prove. And system try to use all possible cases corresponding to goal. Current proving predicate is current goal. During this process if attempt prove to be fail then system return back and try to use alternative case. So solving of task is search of any tree of goals.

Simple program PREDICATES little (symbol) middle (symbol) big (symbol) strong (symbol) powerful (symbol ) CLAUSES little (cat). little (wolf). middle (tiger). middle (bear). big (elephant). big (hippopotamus). strong (tiger). powerful (Animal):- middle (Animal), strong (Animal). powerful (Animal):- big (Animal ).

Goal: powerful (Animal). Try to use rule 1 try to prove middle(Animal) found fact middle(tiger) Animal = tiger try to prove strong(tiger) found fact strong(tiger) Powerful(Animal) is proved Animal = tiger Goal: powerful (elephant). Try to use rule 1 try to prove middle(elephant) fail return back (redo) Try to use rule 2 try to prove big(elephant) found fact big(elephant) Goal is proved

Goal: father(adam,X) Result: father(adam,bill) Who is kids of adam?father(adam,beth) X=bill, X=beth Goal: father(X,bill)Result: father(adam,bill) Who is father of bill?X=adam Goal: grandparent(X,cathy) solving:grandparent(X,cathy) :- parentX,Y), parent(Y,cathy) parent(X,Y) :- father(X,Y) try with redo until Y=cathy result: parent(bill,cathy) X=bill, Y=cathy grandparent(X,Z) :- parent(X, Y ), parent(Y,Z). parent(X, Y ) :- father (X, Y ). parent(X, Y ) :- mother(X, Y ). father (adam, bill). mother(anne, bill). father (adam, beth). mother(anne, beth). father (bill, cathy). mother(cathy, donald). father (donald, eric). mother(diana, eric). female(anne). male(adam). female(beth). male(bill). female(cathy). male(donald). female(diana). male(eric). parent(bill, cathy) :- father(bill,cathy) result: parent(bill,cathy) grandparent(X,cathy) is proved with X=bill

Lists and recursion in Prolog List may be described in 2 forms: [donald, peter, nick]- enumeration [A | Z]- fragmentation in head and tail [donald | Z] In last case as result of unification Z=[peter, nick ] Fragmentation of lists is foundation of recursive programs

Recursion without lists PREDICATES factorial (integer, integer) CLAUSES %factorial 0! equal 1 factorial (0, 1):- !. %factorial n! equal to factorial (n–1)!, multiplied by n factorial (N, Factorial_N):- M=N–1, factorial (M, Factorial_M), Factorial_N=Factorial_M*N. GOAL write (“Input number for calculation of factorial? ”), readint (Number), factorial (Number, Result), write (Number, “!=”, Result).

Calculation 3!

PDC-Prolog. Sections of program CLAUSES contains clauses (main part) PREDICATEScontains descriptions of predicates (its structure), used in program DOMAINScontains descriptions of domains (types of arguments of predicates) GOALcontains predicate-goal used for start of program DATABASEcontains variable part of program, e. i. descriptions of predicates-facts which may be adding and removing during execution of program CONSTANTScontains constants

Example of program /* PROBLEM: A farmer with his goat, wolf and cabbage come to a river that they wish to cross. There is a boat, but it only has room for two, and the farmer is the only one that can row. If the goat and cabbage get in the boat at the same time, the cabbage gets eaten. Similarly, if the wolf and goat are together without the farmer, the goat is eaten. Devise a series of crossings of the river so that all concerned make it across safely. The state of the system is indicated by stating where the farmer, the goat the wolf and the cabbage are located. state( Farmer, Wolf, Goat, Cabbage ) The problem is that a state must only be visited once, and some states are illegal. This is checked by 'unsafe' and 'member'. The Predicate "go" can be called with a start state and a final state go( state(east,east,east,east), state(west,west,west,west) ). */

DOMAINS LOC = east ; west STATE = state(LOC,LOC,LOC,LOC) PATH = STATE* PREDICATES go(STATE,STATE)/* Start of the algorithm */ path(STATE,STATE,PATH,PATH)/* Finds a path from one state to another */ move(STATE,STATE)/* Transfer a system from one side to another*/ opposite(LOC,LOC)/* Gives a location on the opposite side*/ unsafe(STATE)/* Gives the unsafe states*/ member(STATE,PATH)/* Checks if the state is already visited*/ write_path(PATH) write_move(STATE,STATE) show_move(STATE,STATE) showside(LOC,LOC,string) s_river GOAL makewindow(4,7,0,"",0,0,24,80), makewindow(3,7,7," The River ",15,0,10,80), makewindow(2,112,0,"",0,0,1,80), write("press any key for each step of solution"), makewindow(1,7,7," Solutions ",2,0,13,80), show_move(state(west,west,west,west),state(west,west,west,west)), go(state(east,east,east,east),state(west,west,west,west)), write("solved press any key to continue"), readchar(_), exit.

CLAUSES go(S,G):- path(S,G,[S],L), nl,write("A solution is:"),nl, write_path(L), fail. go(_,_). path(S,G,L,L1):-move(S,S1), not( unsafe(S1) ), not( member(S1,L) ), path( S1,G,[S1|L],L1),!. path(G,G,T,T):- !. /* The final state is reached */ move(state(X,X,G,C),state(Y,Y,G,C)):-opposite(X,Y). /* FARMER + WOLF */ move(state(X,W,X,C),state(Y,W,Y,C)):-opposite(X,Y). /* FARMER + GOAT */ move(state(X,W,G,X),state(Y,W,G,Y)):-opposite(X,Y). /* FARMER + CABBAGE */ move(state(X,W,G,C),state(Y,W,G,C)):-opposite(X,Y). /* ONLY FARMER */ opposite(east,west). opposite(west,east):-!. unsafe( state(F,X,X,_) ):- opposite(F,X). /* The wolf eats the goat */ unsafe( state(F,_,X,X) ):- opposite(F,X). /* The goat eats the cabbage */ member(X,[X|_]). member(X,[_|L]):-member(X,L). write_path( [H1,H2|T] ) :- !, readchar(_), write_move(H1,H2), show_move(H1,H2), write_path([H2|T]). write_path( [] ).

write_move( state(X,W,G,C), state(Y,W,G,C) ) :-!, write("The farmer crosses the river from ",X," to ",Y),nl. write_move( state(X,X,G,C), state(Y,Y,G,C) ) :-!, write("The farmer takes the Wolf from ",X," of the river to ",Y),nl. write_move( state(X,W,X,C), state(Y,W,Y,C) ) :-!, write("The farmer takes the Goat from ",X," of the river to ",Y),nl. write_move( state(X,W,G,X), state(Y,W,G,Y) ) :-!, write("The farmer takes the cabbage from ",X," of the river to ",Y),nl. /* Show them move across the river.*/ show_move( state(F,W,G,C), state(F1,W1,G1,C1) ) :-!, s_river, showside(F,F1,"Farmer "), showside(W,W1," Wolf "), showside(G,G1," Goat "), showside(C,C1,"Cabbage"), shiftwindow(1). showside(east,east,Item):-!, write(" ~~~~~ ",Item),nl. showside(west,west,Item):-!, write(" ",Item," ~~~~~ "),nl. showside(east,west,Item):-!, write(" ",Item," <= <= <= ",Item),nl. showside(west,east,Item):-!, write(" ",Item," => => => ",Item),nl. s_river:- shiftwindow(3),clearwindow, write(" WEST river EAST"),nl, write(" "), nl.

Main operators of PDC-Prolog INPUT readln(StringVariable) (string) - (o) readint(IntgVariable) (integer) - (o) readreal(RealVariable) (real) - (o) readchar(CharVariable) (char) - (o) file_str(OSFileName,StringVariable)File String (string,string) - (i,o) (i,i) inkey(CharVariable) (Char) - (o) keypressed()

OUTPUT ====== write( Variable|Constant * ) nl() writef( FormatString, Variable|Constant* ) In the format string the following options are known after a percentage sign: %d Normal decimal number. (chars and integers) %u As an unsigned integer. (chars and integers) %R As a database reference number. (database reference numbers) %X As a long hexadecimal number. (strings, database reference numb). %x As a hexadecimal number. (chars and integers). %s Strings. (symbols and strings). %c As a char. (chars and integers). %g Reals in shortest posible format (default for reals) %e Reals in exponetial notation %f Reals in fixed notation %lf Only for C compatibility (fixed reals) \n - newline \r - carriage return \t - tabulator \nnn - character with code nnn

FILESYSTEM ========== openread(SymbolicFileName,OSFileName) (file,string) - (i,i) openwrite(SymbolicFileName,OSFileName) (file,string) - (i,i) openappend(SymbolicFileName,OSFileName) (file,string) - (i,i) openmodify(SymbolicFileName,OSFileName) (file,string) - (i,i) openfile(SymbolicFileName,OSFileName,OpenMode,FileA ttribute,CreateFlag) (file,string,integer,integer,integer) - (i,i,i,i,i)

WINDOW SYSTEM ============= makewindow(WindowNo,ScrAtt,FrameAtt,Framestr,Row,Column,Height,Width) (integer,integer,integer,string,integer,integer,integer,integer) - (i,i,i,i,i,i,i,i) (o,o,o,o,o,o,o,o) makewindow(WindowNo,ScrAtt,FrameAtt,TitleStr,Row,Column,Height,Width, ClearWindow,TitlePos,BorderChars) (integer,integer,integer,string,integer,integer,integer,integer, integer,integer,string) - (i,i,i,i,i,i,i,i,i,i,i) - (o,o,o,o,o,o,o,o,o,o,o) ClearWindow:0=Don't clear window after creation, 1=do clear. TitlePos:Title pos, value=255 centers title. BorderChars:A 6 character string to build frame. 1st char: Upper left corner 2nd char: Upper right corner 3rd char: Lower left corner 4th char: Lower right corner 5th char: Horizontal line 6th char: Vertical line Ex."┌┐└┘─│" for a single border or"╔╗╚╝═║" for a double border shiftwindow(WindowNo) (integer) - (i) (o)

STRING HANDLING =============== frontchar(String,FrontChar,RestString) (string,char,string) - (i,o,o) (i,i,o) (i,o,i) (i,i,i) (o,i,i) fronttoken(String,Token,RestString) (string,string,string) - (i,o,o) (i,i,o) (i,o,i) (i,i,i) (o,i,i) frontstr(Length,Inpstring,StartString,RestString) (integer,string,string,string) - (i,i,o,o) substring(String,First,NBytes,SubString) (string,integer,integer,string) - (i,i,i,o) subchar(String,CharNo,Char) (string,integer,char) - (i,i,o) searchstring(String,SearchStr,FoundPos) (string,string,integer) - (i,i,o) searchchar(String,Char,FoundPos) (string,char,integer) - (i,i,o) concat(String1,String2,String3) String3 = String1 + String2 (string,string,string) - (i,i,o) (i,o,i) (o,i,i) (i,i,i) str_len(String,Length) (string,integer) - (i,i) (i,o) (o,i) isname(StringParam) (string) - (i)

CONVERSIONS =========== char_int(CharParam,IntgParam) (char,integer) - (i,o) (o,i) (i,i) str_int(StringParam,IntgParam) (string,integer) - (i,o) (o,i) (i,i) str_char(StringParam,CharParam) (string,char) - (i,o) (o,i) (i,i) str_real(StringParam,RealParam) (string,real) - (i,o) (o,i) (i,i) upper_lower(StringInUpperCase,StringInLowerCase) (string,string) - (i,i) (i,o) (o,i) upper_lower(CharInUpperCase,CharInLowerCase) (char,char) - (i,i) (i,o) (o,i) str_ref(Str,Ref) (string,ref) - (i,o) (o,i) (i,i) real_ints(Real,I1,I2,I3,I4) (real,integer,integer,integer,integer) - (i,o,o,o) (o,i,i,i)

HANDLING THE INTERNAL DATABASE ============================== consult(OSFileName) (string) - (i) consult(OSFileName,InternalDatabaseName) (string,InternalDatabaseName) - (i,i) save(OSFileName) (string) - (i) save(OSFileName,InternalDatabaseName) (string,DatabaseName) - (i,i) assert( Term ) (InternalDatabaseDomain) - (i) asserta( Term ) (InternalDatabaseDomain) - (i) assertz( Term ) (InternalDatabaseDomain) - (i)

SCREEN HANDLING =============== EXTERNAL DATABASE SYSTEM ======================== BGI GRAPHIC =========== EDITOR ====== STATUS LINES ============ OS RELATED =========== MISCELLANEOUS MACHINE LOWLEVEL =============================== ERROR & BREAK CONTROL ===================== MESSAGE SUBSYSTEM ================= MISCELLANEOUS ============= CONTROL PREDICATES ================== ARITHMETIC ==========