1 / 58

6.0 PROLOG LAB Using visual PROLOG version 5.2

6.0 PROLOG LAB Using visual PROLOG version 5.2. Example 1: Assume the following “likes” facts knowledge base likes (ali, football). likes (ali, tennis). likes (ahmad, tennis). likes (ahmad, handball). likes (samir, handball). likes (samir, swimming). likes (khaled, horseriding).

Download Presentation

6.0 PROLOG LAB Using visual PROLOG version 5.2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 6.0 PROLOG LAB Using visual PROLOG version 5.2 Example 1: Assume the following “likes” facts knowledge base likes (ali, football). likes (ali, tennis). likes (ahmad, tennis). likes (ahmad, handball). likes (samir, handball). likes (samir, swimming). likes (khaled, horseriding).

  2. To represent the likes facts in VPROLOG A sequence of characters, implemented as a pointer to an entry in a hashed symbol-table, containing strings. The syntax is the same as for strings. • FileNewnoname.pro • Then in the predicate section write the declaration of the used predicates: PREDICATES nondeterm likes (symbol,symbol) • Then in the clauses section write the facts: CLAUSES likes (ali,football). likes (ali,tenis). likes (ahmad,tenis). likes (ahmad,handball). likes (samir,handball). likes (samir,swimming). likes (khaled,horseriding). defines non-deterministic predicates that can backtrack and generate multiple solutions. Predicates declared with the keyword nondeterm can fail and, in this case, do not produce any solution.

  3. 1. Queries as goals in PROLOG • To supply a query in PROLOG put it in the goal section as follows: GOAL likes (ali, football). • Then press Cntrl+G The output will be Yes or No for concrete questions 1. Concrete questions: (queries without variables) Example: GOAL likes(samir, handball).Yes Likes (samir,football). No

  4. 2. Queries with variables • To know all sports that ali likes: likes(ali,What). • To know which person likes teniss likes (Who,tenis). • To know who likes what (i.e all likes facts) likes (Who,What)

  5. 3.Compound queries with one variable • To list persons who likes tennis and football, the goal will be likes( Person, tennis ),likes (Person, football). 2. To list games liked by ali and ahmad likes (ali,Game),likes (ahmad,Game). Person=ali Game=tennis

  6. 4-Compound queries with multiple variables • To find persons who like more than one game: likes(Person, G1),likes (Person,G2),G1<>G2. • To find games liked by more than one person: likes (P1,Game),likes(P2,Game),P1<>P2.

  7. 5. Facts containing variables • Assume we add the drinks facts to the likes database as follows: PREDICATES drinks(symbol, symbol) CLAUSES drinks(ali, pepsi). drinks (samir, lemonada). drinks (ahmad, milk). • To add the fact that all persons drink water: drinks (Everyone, water). • If we put a goal like: drinks (samy,water). drinks (ahmad,water). The answer will be: yes

  8. 6.Rules • Rules are used to infer new facts from existing ones. • A rule consists of two parts: head and body separated by the symbol (:-) . • To represent the rule that express the facts that two persons are friends if they both like the same game: friends( P1,P2):- likes (P1,G),likes (P2,G),P1<>P2. Rule’s symbol The head of the rule The body of the rule

  9. 7.Backtracking in PROLOG • For PROLOG to answer the query : friends (ali, P2). PROLOG will do the following matches and backtracking to the friends rule:

  10. 8.The domains section in VPROLOG • It is used to define domains other than the built-in ones, also to give suitable meanings to predicate arguments. • For example to express the likes relation: likes(person, game) We should first declare person in the domains section as follows: domains person,game= symbol predicates likes (person, game) Person and game are unknown domains(error) This declaration will allow prolog to detect type errors. Example: the query likes(X,Y), likes(Y,Z) will result in a type error, because Y will be matched to a game constant and can not replace a person variable in the second sub goal.

  11. 9. Built-in domains

  12. 10. Basic standard domains

  13. 11. How to do arithmetic operations DOMAINS number=integer PREDICATES addnum(number,number,number) multnum(number,number,number) CLAUSES addnum(X,Y,S):- S=X+Y. multnum(X,Y,P):- P=X*Y. If the goal is: Addnum(5,7,X). Or Multnum(5,7,X). Note:The compound goal: multnum(7,5,X),addnum(X,X,Answer). Will result in X=35, Answer=70 X=12 X=35

  14. 12. More programs to test domains • The isletter(X) predicate gives yes if X is a letter: PREDICATES isletter(char) CLAUSES isletter(Ch):- ‘a’<=Ch, Ch<=‘z’. isletter(Ch):- ‘A’<=Ch, Ch<=‘Z’. To test this program, give it the following goals: a- isletter(‘x’).  yes b- isletter(‘2’).  no c- isletter(“hallo”).  type error d- isletter(a).  Type error e- isletter(X)  free variable message

  15. 13. Multiple aritypredicates overloading • The arity of a predicate is the number of arguments that it takes. • You can have two predicates with the same name but with different arities. • You must group different arity versions of a given predicate name in both the predicate and clauses sections. • The different arities predicates are treated as different predicates.

  16. 14. Example: for multiple arity predicates DOMAINS person=symbol PREDICATES nondeterm father (person) nondeterm father (person, person) CLAUSES father (Man):- father (Man,_). father (ali, ahmad). father (samy, khaled). Anonymous variable can match anything. A person is said to be a father if he is a father of any one.

  17. 15. A complete expert system that decides how a person can buy a car. • Assuming • A person is described by the two relations: salary (person, money) savings (person, money) • A car for sale is described by the two relations: cash (cartype, money) takseet(cartype,money)

  18. A person can buy a car -with cash money if one third of his savings is greater or equal to the cash price of the car. -with takseet if one third of his salary is greater or equal to the price of the car in case of cash divided by 30. - If the person can buy a car using cash or takseet the system will advice him to buy with cash

  19. The VPROLOG program DOMAINS person, car =symbol money=real way=string PREDICATES salary (person, money) savings (person, money) cash (car, money) takseet (car, money) canbuy (person, car,way) howcanbuy (person, car,way)

  20. CLAUSES cash (cressida,15000). cash (camri,55000). cash (caprise82,5000). cash (caprise90,8000). cash (landcruizer2003,100000). takseet (Car, TPrice):- cash (Car, Price), TPrice=Price*1.2. canbuy ( Person, Car, “cash”):- savings (Person, M), cash( Car, N), M/3>=N. canbuy ( Person,Car, “takseet”):- salary (Person, M), takseet(Car,T),M/3>=T/30.

  21. OR howcanbuy (Person,Car,Way):- canbuy (Person,Car,Way),Way="cash"; canbuy (Person, Car, Way), Way="takseet", NOT(canbuy (Person,Car,"cash")). Should be placed around expressions which include only constants and /or bounded variables. These variables will be bounded before reaching the “not” expression containing them

  22. 16. Controlling Backtracking DOMAINS name=symbol PREDICATES nondeterm father(name,name) everybody CLAUSES father (ali, salem). father (ahmad, ibrahim). father (ahmad, zaynab). everybody:- father (X,Y), write (X,” is ” ,Y,”’s father\n” ), fail. everybody. GOAL everybody. • The fail Predicate: • V Prolog begins backtracking when a call fails. • The fail predicate is used to force backtracking. • The following program uses fail to get all solutions. • Without fail we will get only one solution. To make the goal succeed at the end

  23. Preventing backtracking by the cut (!) • It is impossible to backtrack across a cut. • Green cut: it is a cut used to prevent solutions which does not give meaningful solutions. • Red cut : it is a cut used to prevent alternate subgoals. • Example: to prevent backtracking to previous subgoals: r1:- a, b, !, c. r1:-d. Only first solution to a and b is considered with many solutions for c this clause for r1 will not be considered if a solution is found in the above rule.

  24. 17. Highway Map modelling and recursive rules a 4 b • To represent the shown map we use the predicate link ( node, node, distance) • To find a path from s to d • get it from mentioned facts : path (S,D, TDist):-link (S, D, TDist). • Or find a node x which has a link from S to X and a path from X to D as follows: path (S,D, TDist):- link (S,X,DS1),path (X,D,DS2), TDist=DS1+DS2. 2 5 c 6 5 g 3 d link(a,b,4). link (a,c,2). link (b,g,5). link (c ,g,6). link (c,d,5). link (d,g,3). Total distance

  25. The complete path distance finder program DOMAINS node=symbol distance= integer PREDICATES nondeterm link (node, node, distance) nondeterm path ( node, node, distance) CLAUSES link(a,b,4). link (a,c,2). link (b,g,5). link (c ,g,6). link (c,d,5). link (d,g,3). path (S,D, TDist):-link (S, D, TDist). path (S,D, TDist):- link (S, X, TD1 ),path (X,D,TD2), TDist=TD1+TD2. GOAL path (a, g, TotalDistance). Facts that model the road map Recursive rule TotalDistance=9 TotalDistance=8 TotalDistance=10 3 Solutions output

  26. 18. Rules which behave like procedures greet:- write(“ASalamo Alykom”),n1. • A rule that when its head is found in a goal will print something. • Rules used like case statements: Only rules with matching arguments will be executed, others will be tested but will fail. PREDICATES nondeterm action (integer) CLAUSES action(1):- nl, write (“N=1”),nl. action(2):- nl, write (“N=2”),nl. action(3):- nl, write (“N=3”),nl. action (N):- nl, N<>1,N<>2,N<>3,write (“N=?”),nl. GOAL write (“Type a number 1->3”), readint (N) , action(N).

  27. PREDICATES nondeterm action (integer) CLAUSES action(1):-!, nl, write (“N=1”),nl. action(2):- !,nl, write (“N=2”),nl. action(3):- !,nl, write (“N=3”),nl. action (_):- nl, ,write (“unknown number ?”),nl. GOAL write (“Type a number 1->3”), readint (N) , action(N). • Since rules that has unmatched arguments will be tested and will fail. This will slow the program. To speed up the system use the cut as shown. • If you want to test a range x>5 and <9 place the cut after the test sub goals. Action(X):- X>5,X<9,!,write(“5<N<9”),n1.

  28. To make a rule return a value • To define a rule which classifies a number either positive, negative or zero: PREDICATES nondeterm classify (integer,symbol). CLAUSES classify( X,pos):- X>0. classify( X,neg):- X<0. classify( X,zero):- X=0. Goal Classify ( 5,What) Classify (-4,What) Classify (X,What) What carries the returned result What carries the returned result What=pos What=nig error

  29. 19. Compound data objects • Compound data objects allow you to treat several pieces of information as a single item (like structures in c, c+, or c#). • Example: to represent a date object: DOMAINS date_cmp= date(string, unsigned, unsigned) Hence in a rule or goal you can write: ..,D=date(“March”,1,1960). Here D will be treated as a single item. called : functor

  30. The arguments of a compound object can themselves be compound: Example : to represent the information for the birthday of a person:- birthday(person(“ahmad”,”ali”),date(1,”march”,1960)( DOMAINS birthday= birthday (person, date) person = person (name, name) date= date (day, month, year) name, month =string day, year= unsigned BIRTHDAY PERSON DATE Ahamd Ali 1 March 1960

  31. 19.1 A family birthday program Compound objects DOMAINS person = person (name, name) birthdate= bdate (day, month, year) name, month =string day,year= unsigned PREDICATES nondeterm birthday (person, bdate) CLAUSES birthday(person("amin","mohamad"),bdate(1,"March",1960)). birthday(person("mohamd","amin"),bdate(11,"Jan",1988)). birthday(person("abdo","mohamad"),bdate(11,"Oct",1964)). birthday(person("ali","mohamad"),bdate(1,"Feb",1950)). birthday(person("suzan","antar"),bdate(1,"March",1950)). GOAL %birthday(X,Y). %birthday(X,date(_,"March",_)). %birthday(person(X,"mohamad"),bdate(_,_,Y).( Lists all birthday’s person, and date objects Lists persons born on March Lists persons whose second name is “mohamd” with year of birth

  32. 19.2 Using system date DOMAINS person = person (name, name) bdate= bdate (day, month, year) name=string day ,month, year= unsigned PREDICATES nondeterm birthday (person, bdate) get_birth_thismonth testnow (unsigned, bdate) write_person(person) CLAUSES birthday(person("amin","mohamad"),bdate(1,3,1960)). birthday(person("mohamd","amin"),bdate(11,5,1988)). birthday(person("abdo","mohamad"),bdate(11,5,1964)). birthday(person("ali","mohamad"),bdate(1,6,1950)). birthday(person("suzan","antar"),bdate(1,3,1982)). get_birth_thismonth:- date (_,Thism ,_), write ( “now month is", Thism), nl, birthday (P, D), testnow(Thism, D), write_person(P), fail. get_birth_thismonth:-write (“Press any key to continue"), nl, readchar(_). testnow(TM,bdate (_,BM,_)):- TM=BM. write_person(person(Fn, Ln)):-write(" ", Fn, "\t\t ", Ln), nl. GOAL get_birth_thismonth.

  33. 19.3 Using alternatives in domain declaration • Assume we want to declare the following statements: • Ali owns a 3-floar house • Ali owns a 4-door car • Ali owns a 3.2 Ghz computer • To define a thing to be either house, car, or computer: DOMAINS thing= house( nofloars); car (nodoors); computer(ghertz) nofloars,nodoors=integer ghertz=real person= person(fname, lname) fname, lname=symbol PREDICATES nondeterm owns(person, thing) CLAUSES owns( person(mohamad, ali), house(3)). owns(person(mohamd,ali),computer(3.2)). Use or(;) to separate alternatives. goal owns (P,X). 2 solutions

  34. 19.4 Lists Here, the teacher name is repeated many times. We need a variable length data structure that holds all subjects that a teacher can teach • To declare the subjects a teacher might teach: PREDICATES teacher (symbol, symbol, symbol) CLAUSES teacher (ahmad, ezz,cs101). teacher (ahmad, ezz, cs332). teacher (amin, mohamad, cs435). teacher (amin,mohamad, cs204). teacher (amin,mohamad, cs212). teacher (reda, salama, cs416). teacher (reda, salama,cs221). Solution: use a list data structure for the subject Solution use a list data structure for the subject DOMAINS subject=symbol * PREDICATES teacher (symbol,symbol,subject) CLAUSES teacher(ahmad, ezz,[cs101,cs332] ) teacher (amin,mohamad, [cs204, cs435, cs212] ). teacher (reda,salama, [cs416, cs221] ).

  35. 20. Repetition and Recursion • Repetition can be expressed in PROLOG in procedures and data structures. • Two kinds of repetition exist in PROLOG : Backtracking: search for multiple solutions Recursion: a procedure calls itself When a sub goal fails, PROLOG returns to the most recent subgoal that has an untried alternative. Using the fail predicate as the end of repeated subgoals we enforce PROLOG to repeat executing different alternatives of some subgoals. Normal recursion: Takes a lot of memory and time Tail recursion: fast and less memory Compiled into iterative loops in M/C language

  36. 20.1 Repetition using backtracking • Example: Using fail to print all countries: PREDICATES nondeterm country (symbol) print_countries CLAUSES country (“Egypt”). country (“SaudiArabia”). country ( “Seria”). country (“Sudan”). print_countries:- country(X), write(X), nl, fail. print_countries. GOAL print_countries.

  37. To do pre-actions (before the loop )or post-actions (after the loop), write different versions of the same predicate. 20.1.2 Pre and post actions • PREDICATES • nondeterm country (symbol) • nondeterm print_countries • CLAUSES • country ("Egypt"). • country ("SaudiArabia"). • country ( "Seria"). • country ("Sudan"). • print_countries:- • write("Some Arabic countries are"),nl,fail. • print_countries:- country(X), write(X," and "), fail. • print_countries:- • nl, write("there are others"), nl. • GOAL • Print_countries. Pre-action Some Arabic countries are Egypt and SaudiArabia and Seria and Sudan There are others Post-action Main-action

  38. 20.2 Implementing backtracking with loops PREDICATES repeat typewriter CLAUSES repeat. repeat:- repeat. trypewriter:- repeat, readchar(C), write(C) , C=‘\r’,! . /* if CR then cut • The following repeat predicate tricks PROLOG and makes it think it has infinite solutions: repeat. repeat:- repeat. The shown program uses repeat to keep accepting a character and printing it until it is CR Nth solution 1st solution (N+1)th solution Multiple solutions attract backtracking when fail occurs 2nd solution

  39. 20.3 Recursive procedures PREDICATES factorial (unsigned, real) CLAUSES factorial (1,1):-!. factorial (N, FactN):- M=N-1, factorial (M, FactM), FactN=N*FactM. Goal factorial (5,F). • To find the factorial of a number N : FACT(N) IF N=1 then FCT(N)=1 Else FACT(N)=N* FACT(N-1) • Using PROLOG, the factorial is implemented with two versions of the factorial rule as shown here. F=120 1 Solution

  40. 20.4 Tail Recursion • Occurs when a procedure calls itself as the last step. • Occurs in PROLOG ,when • The call is the very last subgoal in a clause. • No backtracking points exist before this call. • The recursive predicate does not return a value. • Only one version of this predicate exists. • Example: count (N):- write(N), nl, NewN=N+1, count (NewN). GOAL count(0). No alternative solutions here No alternative solutions here (2) No alternative solutions exist here no backtracking points (3)N is bound to a constant value and no other free variable no return value (1) Last call no need to save state of the previous call stack is free no extra memory is needed small memory and fast due to no need to push state You can use a cut(!) before the last call to be sure of (2). Write numbers from 0 to infinity ( will get unexpected values due to overflow)

  41. 20.5 Using arguments as loop variables PREDICATES factorial (unsigned, long) factorial_r(unsigned, long, unsigned, long) CLAUSES factorial (N, FactN):- factorial_r(N, FactN,1,1). factorial_r( N, FactN, I, P):- I<=N, ! , NewP=P*I, NewI=I+1, factorial_r(N,FactN,NewI,NewP). factorial_r(N, FactN ,I ,P):- I>N, FactN=P. • To implement factorial with iterative procedure using C-language: long fact; long p=1; unsigned i=1; while(i<=n) { p=p*i; i=i+1; } fact=p; Initialize arguments I,P Test end condition to go to other versionif not satisfied. To prevent backtracking and to allow tail recursion.

  42. 21. Lists and Recursion • List processing allows handling objects that contain an arbitrary number of elements. • A list is an object that contains an arbitrary number of other objects. • A list that contains the numbers 1,2 and 3 is written as [1,2,3] . • Each item contained in a list is know as an element. • To declare the domain of a list of integers: • Domains • intlist= integer * Means list of integers Could be any other name ( ilist, il,…)

  43. The elements of a list must be of a single domain. • To define a list of mixed types use compound objects as follows: • Domains • elementlist= element * • element=ie (integer); re ( real); se (string) • A list consists of two parts: • The head : the first element of the list • The tail : a list of the remaining elements. • Example: if l=[a,b,c] the head is a and the tail is [b, c]. The Tail The Headt

  44. If you remove the first element from the tail of the list enough times, you get down to the empty list ([ ]). • The empty list can not be broken into head and tail. • A list has a tree structure like compound objects. • Example: the tree structure of [a, b,c, d] is drawn as shown in the figure. list list a Note : the one element list [a] is not as the element a since [a] is really the compound data structure shown here b list [a] c list a [ ] d [ ]

  45. 21.1 List processing • Prolog allows you to treat the head and tail explicitly. You can separate the list head and tail using the vertical bar (|). • Example : • [a, b, c ] ≡[a |[b, c ] ] ≡[a |[b| [c ] ]] ≡[a | [b| [c| [] ] ] ] ≡[a , b| [c ] ]

  46. 21.2 List unification: the following table gives examples of list unification:

  47. DOMAINS list= integer * PREDICATES write_a_list( list ) CLAUSES write_a_list([ ]). write_a_list ( [ H | T ] ):- write(H), nl, write_a_list( T). GOAL write_a_list([ 1, 2, 3]). • 21.3 Using lists • Since a list is really a recursive compound data structure, you need recursive algorithms to process it. • Such an algorithm is usually composed of two clauses:- • One to deal with empty list. • The other deals with ordinary list (having head and tail). • Example: the shown program writes the elements of an integer list. Do nothing but report success. T=[ ] Write the head Write the Tail list

  48. 21.4 Counting list elements DOMAINS list= integer * PREDICATES length_of ( list, integer) CLAUSES length_of ( [], 0). Length_of ( [ H | T ],L ):- length_of ( T ,M ), L=M+1. GOAL length_of([ 1, 2, 3],L). • Two logical rules are used to determine the length of a list • The length of [ ] is 0. • The length of the list [X|T] is 1+the length of T. • The shown Prolog program counts the number of elements of a list of integers (can be used for any type). T=[ ] L=3 Homework: modify the length program to calculate the sum of all elements of a list

  49. 21.5 Modifying the list DOMAINS list= integer * PREDICATES add1 ( list, list) CLAUSES add1 ( [], []). add1 ( [ H1 | T1 ],[H2|T2] ):- H2=H1+1, add1( T1,T2). GOAL add1( [ 1, 2, 3], L ). • The following program adds 1 to each element of a list L1 by making another list L2: • If L1 is [ ] then L2=[ ] • If L1=[H1|T1] assuming L2=[H2|T2] then • H2=H1+1. • Add 1 to T1 by the same way L=[ 2, 3, 4]

  50. 21.6 Removing Elements from a list DOMAINS list= integer * PREDICATES discard_NG ( list, list) CLAUSES discard_NG ( [], []). discard_NG ( [ H1 | T1 ],L2 ):- H1<0, !, discard_NG(T1,L2). discard_NG ( [ H1 | T1 ],[H1|T2] ):- discard_NG(T1,T2). GOAL discard_NG( [ 1, -2, 3], L ). • The following program removes negative elements from a list L1 by making another list L2 that contains non negative numbers of L1 : • If L1 is [ ] then L2=[ ] • If L1=[H1|T1] and H1<0 then neglect H1 and process T1 • Else make head of L2 H2=H1 and Repeat for T1. L=[ 1, 3]

More Related