41
Introduction to Prolog Introduction to Prolog Facts, Questions & Rules Facts, Questions & Rules Atoms & Variables Atoms & Variables

Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Embed Size (px)

Citation preview

Page 1: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Introduction to PrologIntroduction to Prolog

Facts, Questions & RulesFacts, Questions & Rules

Atoms & VariablesAtoms & Variables

Page 2: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

LISP/Prolog DataLISP/Prolog Data

LISP/Prolog developed for AILISP/Prolog developed for AI– LISP in late 1950sLISP in late 1950s– Prolog in mid-late 1970sProlog in mid-late 1970s

Artificial Intelligence = intelligent artifactArtificial Intelligence = intelligent artifact Ability to Ability to perceive, reasonperceive, reason and and actact

– LISP/Prolog concerned mostly with reasoningLISP/Prolog concerned mostly with reasoning– Symbolic manipulation of (model of) worldSymbolic manipulation of (model of) world

Page 3: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Symbolic ProgrammingSymbolic Programming

Most languages work with numbers & textMost languages work with numbers & text– Also more complicated combinations of sameAlso more complicated combinations of same

Prolog/LISP work with symbolsProlog/LISP work with symbols– Also work with numbers & textAlso work with numbers & text– Not as suitable for numeric/textual programsNot as suitable for numeric/textual programs

Symbols represent things in the worldSymbols represent things in the world– Language makes it easy to use themLanguage makes it easy to use them

Page 4: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

PrologProlog

PROgrammation en LOGiquePROgrammation en LOGique– PROgramming in LOGicPROgramming in LOGic

Logic modelLogic model– Program = axiomsProgram = axioms– Execution gives theoremsExecution gives theorems

Restricted logic – can’t say as muchRestricted logic – can’t say as much

Page 5: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Logic ModelLogic Model

Proof (Proof (vs. Commandvs. Command)) ProcessProcess

– predicate specificationpredicate specification assertionsassertions– predicate applicationpredicate application questionsquestions

DataData– mathematical objectsmathematical objects atoms, lists & termsatoms, lists & terms

Page 6: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Prolog FactsProlog Facts

Simply state what’s trueSimply state what’s true– Need to decide on symbols to state axiomsNeed to decide on symbols to state axioms

Family factsFamily factsparent(mark, alex).parent(mark, alex). % Mark is Alex’s % Mark is Alex’s

parentparentparent(di, alex).parent(di, alex). % Di is Alex’s parent% Di is Alex’s parentparent(bob, mark).parent(bob, mark). % Bob is Mark’s % Bob is Mark’s

parentparent% sign starts a comment

Comment continues to end of line

Page 7: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Prolog AtomsProlog Atoms

mark, di, alex & bob are mark, di, alex & bob are notnot variables variables Atoms are themselves and nothing elseAtoms are themselves and nothing else

– an atom does not have a valuean atom does not have a value– only one atom with any given name (no local only one atom with any given name (no local

scope, only global)scope, only global) Named atoms start with lower-case letterNamed atoms start with lower-case letter

– may contain letters (UPPER and lower case), may contain letters (UPPER and lower case), numbers & underscoresnumbers & underscores

Page 8: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Syntax of Prolog FactsSyntax of Prolog Facts

Consist of Consist of functor…functor… parentparent– AKA AKA name of the predicatename of the predicate

……and and argumentsarguments mark, alexmark, alex Arguments in (parentheses)…Arguments in (parentheses)…

– Right up against the functorRight up against the functor ……separated, by, commasseparated, by, commas Ends with a period.Ends with a period.

– Can be split over multiple lines, if you likeCan be split over multiple lines, if you like

Page 9: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Syntax of Prolog FactsSyntax of Prolog Facts

parent( mark, alex ).parent( mark, alex ).

parentparent( mark, alex ).( mark, alex ). % functor% functor

parentparent(( mark, alexmark, alex )).. % parentheses% parentheses

parent( parent( markmark, alex )., alex ). % 1% 1stst argument argument

parent( markparent( mark,, alex ).alex ). % comma% comma

parent( mark, parent( mark, alexalex ). ). % 2% 2ndnd argument argument

parent( mark, alex )parent( mark, alex ).. % period% period

Page 10: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

RepresentationsRepresentations

Parenthood a relationship with two peopleParenthood a relationship with two people– parentparent represents the relationship represents the relationship– markmark and and alexalex represent the people represent the people– Position distinguishes parent from childPosition distinguishes parent from child– Note: all start with Note: all start with lowercaselowercase letters letters

Arity Arity of parenthood relationship is 2of parenthood relationship is 2– TheThe predicate predicate is parent/2 is parent/2– MayMay be other predicates with same name be other predicates with same name

Page 11: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

% parents(Child, Father, Mother)% parents(Child, Father, Mother)parents(mark, bob, isabel).parents(mark, bob, isabel).

% Mark’s dad & mom are Bob And Isabel % Mark’s dad & mom are Bob And Isabel

% parent(Parent, Child)% parent(Parent, Child)parent(mark, alex).parent(mark, alex). % Mark is Alex’s parent% Mark is Alex’s parent

Multiple RepresentationsMultiple Representations

Choose based on how info to be usedChoose based on how info to be used

% father(Child, Parent)% father(Child, Parent)father(alex, mark).father(alex, mark). % Alex’s father is Mark% Alex’s father is Mark

Page 12: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

ExerciseExercise

Write a set of facts about Write a set of facts about youryour family using family using the second representation above.the second representation above.– your parents’ family if you don’t have oneyour parents’ family if you don’t have one

My family:My family:parents(mark, bob, isabel).parents(mark, bob, isabel).parents(di, ralph, esther).parents(di, ralph, esther).parents(alex, mark, di).parents(alex, mark, di).parents(zachary, mark, di).parents(zachary, mark, di).

Page 13: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Program FileProgram File

A program A program may may consist of just factsconsist of just facts– family_1.plfamily_1.pl

Want to start Prolog, assert the facts, and Want to start Prolog, assert the facts, and then start asking questionsthen start asking questions– We want to We want to consultconsult the file the file– Windows – double-click file to start Prolog and Windows – double-click file to start Prolog and

file is consulted automaticallyfile is consulted automatically– Linux – need to use consult/1 predicateLinux – need to use consult/1 predicate

Page 14: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Some Predicates to Start WithSome Predicates to Start With

?- ?- help.help. % general help% general help

?- ?- help(help).help(help). % help on …% help on …

?- ?- apropos(help).apropos(help). % help available ...% help available ...

?- ?- consult(‘family_1.pl’).consult(‘family_1.pl’). % load a file% load a file

?- ?- [‘family_1.pl’].[‘family_1.pl’]. % ditto% ditto

?- ?- edit(‘family_1.pl’).edit(‘family_1.pl’). % edit/reload file% edit/reload file

?- ?- [user].[user]. % enter facts interactively% enter facts interactively

?- ?- halt.halt. % exit Prolog% exit Prolog

Page 15: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Asking Yes/No QuestionsAsking Yes/No Questions

Can ask about parentageCan ask about parentage ?- is Prolog prompts for a question?- is Prolog prompts for a question

– type in (what looks like) a facttype in (what looks like) a fact– Prolog will tell you if it’s in the databaseProlog will tell you if it’s in the database

?- ?- parent(mark, alex).parent(mark, alex).yesyes?- ?- parent(bob, di).parent(bob, di).nono

Page 16: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Show Prolog’s Response…Show Prolog’s Response…

parent(mark, alex).parent(mark, alex).

parent(di, alex).parent(di, alex).

parent(bob, mark).parent(bob, mark).

parent(isabel, mark).parent(isabel, mark).

parent(ralph, di).parent(ralph, di).

parent(esther, di).parent(esther, di).

parent(franklin, bob).parent(franklin, bob).

?- ?- parent(mark, alex).parent(mark, alex).

?- ?- parent(ralph, esther).parent(ralph, esther).

?- ?- parent(alex, mark).parent(alex, mark).

?- ?- parent(ralph, di).parent(ralph, di).

Page 17: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Asking Who QuestionsAsking Who Questions

Can also ask Can also ask whowho is parent of is parent of whomwhom?- ?- parent(Who, mark).parent(Who, mark).

Who = bobWho = bob

yesyes Prolog pauses after saying who Who isProlog pauses after saying who Who is

– Press Enter or space to signal you’re readyPress Enter or space to signal you’re ready– (systems differ in what keys to press)(systems differ in what keys to press)

Page 18: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Asking Whom QuestionsAsking Whom Questions

Can also ask Can also ask whowho is parent of is parent of whomwhom?- ?- parent(bob, Whom).parent(bob, Whom).Whom = markWhom = markyesyes

?- ?- parent(Who, Whom).parent(Who, Whom).Who = markWho = markWhom = alexWhom = alexyesyes

Page 19: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

VariablesVariables

Words that start with Capital Letters are Words that start with Capital Letters are variablesvariables– More accurately “unknowns”More accurately “unknowns”

If you ask a question with variables, Prolog If you ask a question with variables, Prolog says what values they could have to make says what values they could have to make what you wrote truewhat you wrote true– If there’s no such, Prolog just says noIf there’s no such, Prolog just says no

Page 20: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Show Prolog’s Response…Show Prolog’s Response…

parent(mark, alex).parent(mark, alex).

parent(di, alex).parent(di, alex).

parent(bob, mark).parent(bob, mark).

parent(isabel, mark).parent(isabel, mark).

parent(ralph, di).parent(ralph, di).

parent(esther, di).parent(esther, di).

parent(franklin, bob).parent(franklin, bob).

?- ?- parent(Who, bob).parent(Who, bob).

?- ?- parent(ralph, Whom).parent(ralph, Whom).

?- ?- parent(alex, Whom).parent(alex, Whom).

Page 21: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Variables & NoVariables & No

““Closed world assumption”Closed world assumption”– if it’s not in the database, it isn’t trueif it’s not in the database, it isn’t true– everything relevant to the question is knowneverything relevant to the question is known

?- ?- parent(garvie, franklin).parent(garvie, franklin).nono ““no” means “don’t know of any”no” means “don’t know of any”?- ?- parent(Who, isabel).parent(Who, isabel).nono

Page 22: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Variable NamesVariable Names

Prolog doesn’t care about the namesProlog doesn’t care about the names?- ?- parent(bob, X).parent(bob, X).X = markX = markyesyes?- ?- parent(bob, Child).parent(bob, Child).Child = markChild = markyesyes?- ?- parent(alex, Anyone).parent(alex, Anyone).nono

use meaningful variable namesX usually not good

Page 23: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Multiple AnswersMultiple Answers

Sometimes more than one correct answerSometimes more than one correct answer?- ?- parent(Who, alex).parent(Who, alex).Who = mark Who = mark ;;Who = di Who = di ;;nono Type a semi-colon to get next answerType a semi-colon to get next answer

– n and r also workn and r also work– (different systems use different characters)(different systems use different characters)

Semi-colons here mean – “are there more answers?”

This “no” means there were no more answers

Page 24: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Asking Anybody QuestionsAsking Anybody Questions

Start the variable with an underscoreStart the variable with an underscore– Prolog won’t tell you its valueProlog won’t tell you its value

?- ?- parent(mark, _Anybody).parent(mark, _Anybody).yesyes

?- ?- parent(Parent, _Anyone).parent(Parent, _Anyone).Parent = mark Parent = mark ;;Parent = di Parent = di yesyes

Why did it say “yes” here instead of “no”?And why didn’t it find Bob?

Is mark anyone’s parent(don’t care who, just whether)

Page 25: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Show Prolog’s Response…Show Prolog’s Response…

parent(mark, alex).parent(mark, alex).

parent(di, alex).parent(di, alex).

parent(bob, mark).parent(bob, mark).

parent(isabel, mark).parent(isabel, mark).

parent(ralph, di).parent(ralph, di).

parent(esther, di).parent(esther, di).

parent(franklin, bob).parent(franklin, bob).

?- ?- parent(Who, di).parent(Who, di).

(show all (show all answers)answers)

?- ?- parent(_Who, alex).parent(_Who, alex).

?- ?- parent(alex, _Whom).parent(alex, _Whom).

Page 26: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Compound QuestionsCompound Questions

Separate terms with commasSeparate terms with commas– Still just one questionStill just one question– All things must be true, so comma = ANDAll things must be true, so comma = AND

?- ?- parent(GP, P), parent(P, C).parent(GP, P), parent(P, C).GP = bobGP = bobP = markP = markC = alexC = alexyesyes

Important Note: -- P appears twice in the question -- only gets one value -- same value in both places

Page 27: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Single AssignmentSingle Assignment

Each variable can only have one value in Each variable can only have one value in one answerone answer

?- ?- parent(GP, P), parent(P, C).parent(GP, P), parent(P, C). Find GP, P and C such thatFind GP, P and C such that

– GP is a parent of P, GP is a parent of P, andand – P is a parent of CP is a parent of C

Variable can only have different values in Variable can only have different values in different answersdifferent answers

Page 28: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

ExerciseExercise

Answer these questions based on the Answer these questions based on the database on pp. 1 & 2 of the textdatabase on pp. 1 & 2 of the text

?- ?- parent(pam, Whom).parent(pam, Whom).

?- ?- parent(tom, Whom).parent(tom, Whom). % give all answers% give all answers

?- ?- parent(bob, Child), parent(Child, _Any).parent(bob, Child), parent(Child, _Any).

?- ?- parent(Ann, jim).parent(Ann, jim). % careful!% careful!

?- ?- parent(pam, Whom), parent(Who, liz).parent(pam, Whom), parent(Who, liz).

?- ?- parent(tom, _Any), parent(_Any, GChild).parent(tom, _Any), parent(_Any, GChild).

Page 29: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

RulesRules

That compound question is one we might That compound question is one we might want to ask oftenwant to ask often– Who is the grandparent of whomWho is the grandparent of whom

New predicate: grandparent/2New predicate: grandparent/2– First argument is grandparent of secondFirst argument is grandparent of second

grandparent(GP, C) :- parent(GP, P), parent(P, C).grandparent(GP, C) :- parent(GP, P), parent(P, C).– This is a This is a rulerule, and we can put it in the file, and we can put it in the file

Page 30: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Using RulesUsing Rules

Just ask the questionJust ask the question?- ?- grandparent(ralph, alex).grandparent(ralph, alex).yesyes

?- ?- grandparent(GP, C).grandparent(GP, C).GP = bobGP = bobC = alexC = alexyesyes Note – parent not mentioned in the answerNote – parent not mentioned in the answer

Page 31: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Understanding RulesUnderstanding Rules

Consists of Consists of head head and and bodybody– Head and body separated by colon-hyphenHead and body separated by colon-hyphen

Head Head is just like a factis just like a fact– Tho’ it Tho’ it usuallyusually has variables as arguments has variables as arguments

BodyBody is like a question is like a question– It’s usually compound (separated by commas)It’s usually compound (separated by commas)

Variables connect arguments togetherVariables connect arguments together

Page 32: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Rules in More DetailRules in More Detail

grandparent(GP, C) :-grandparent(GP, C) :-parent(GP, P),parent(GP, P),parent(P, C).parent(P, C).

Note the way it’s Note the way it’s writtenwritten– IndentationIndentation– PunctuationPunctuation

GP is a grandparent of C GP is a grandparent of C if if there is some P such there is some P such thatthat– GP is a parent of P, GP is a parent of P, andand– P is a parent of CP is a parent of C

Page 33: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Rule DiagramsRule Diagrams

May help you seeMay help you see Define grandparent/2 Define grandparent/2

predicatepredicate– GP = grandparentGP = grandparent– C = childC = child

True if there’s a P True if there’s a P “between” them“between” them– GP parent of PGP parent of P– P parent of CP parent of C

C

GP

P

parent

parent

grandparent

Page 34: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

ClausesClauses

Facts and rules are called Facts and rules are called clausesclauses A predicate can be made up of any number A predicate can be made up of any number

of clausesof clauses– All facts, all rules, or some of eachAll facts, all rules, or some of each– Usually kept together, but need not beUsually kept together, but need not be

Looking at a predicate:Looking at a predicate:?- listing(PredicateName).?- listing(PredicateName).?- listing(PredicateName/Arity).?- listing(PredicateName/Arity).

Page 35: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Multi-Clause RulesMulti-Clause Rules

Two ways to be an uncleTwo ways to be an uncleuncle(Uncle, NieceOrNephew) :-uncle(Uncle, NieceOrNephew) :-

parent(Parent, NieceOrNephew),parent(Parent, NieceOrNephew),brother(Uncle, Parent).brother(Uncle, Parent).

uncle(Uncle, NieceOrNephew) :-uncle(Uncle, NieceOrNephew) :-parent(Parent, NieceOrNephew),parent(Parent, NieceOrNephew),sister(Aunt, Parent),sister(Aunt, Parent),husband(Uncle, Aunt).husband(Uncle, Aunt).

Still need to definebrother/2, sister/2 & husband/2.

Page 36: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Uncle ExampleUncle Example

parent(mark, alex).parent(mark, alex).

parent(di, alex).parent(di, alex).

brother(brian, mark).brother(brian, mark).

sister(cathy, di).sister(cathy, di).

wife(susan, brian).wife(susan, brian).

husband(brad, cathy).husband(brad, cathy).

?- ?- uncle(Who, alex).uncle(Who, alex).

Who = brian Who = brian ;;

Who = brad Who = brad ;;

nono

Page 37: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

ExerciseExercise

parent(mark, alex).parent(mark, alex).

parent(di, alex).parent(di, alex).

brother(brian, mark).brother(brian, mark).

sister(cathy, di).sister(cathy, di).

wife(susan, brian).wife(susan, brian).

husband(brad, cathy).husband(brad, cathy).

Who are Alex’s Who are Alex’s aunts?aunts?

Write a definition Write a definition of aunt/2of aunt/2– aunt(Aunt, NorN).aunt(Aunt, NorN).

Page 38: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

RecursionRecursion

Predicates may be recursivePredicates may be recursive– Needs a base case – fact or non-recursive ruleNeeds a base case – fact or non-recursive rule

ancestor(Anc, Desc) :-ancestor(Anc, Desc) :-parent(Anc, Desc).parent(Anc, Desc).

ancestor(Anc, Desc) :-ancestor(Anc, Desc) :-parent(Parent, Desc),parent(Parent, Desc),ancestor(Anc, Parent).ancestor(Anc, Parent).

Usually write base case first – more laterUsually write base case first – more later

Base case: your parent is your ancestor

Recursive case: an ancestor of your parent is your ancestor

Page 39: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Rule DiagramsRule Diagrams

Each diagram a Each diagram a clauseclause

Note recursionNote recursion– Needs base caseNeeds base case

D

A

parent ancestor

D

A

P

ancestor

parent

ancestor

Page 40: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Alex’s AncestorsAlex’s Ancestors

parent(mark, alex).parent(mark, alex).parent(bob, mark).parent(bob, mark).parent(franklin, bob).parent(franklin, bob).parent(garvie, franklin).parent(garvie, franklin).

ancestor(A, D) :-ancestor(A, D) :-parent(A, D).parent(A, D).

ancestor(A, D) :-ancestor(A, D) :-parent(P, D),parent(P, D),ancestor(A, P).ancestor(A, P).

?- ?- ancestor(Who, alex).ancestor(Who, alex).

Who = markWho = mark ; ;

Who = bobWho = bob ; ;

Who = franklinWho = franklin ; ;

Who = garvieWho = garvie ; ;

nono

Page 41: Introduction to Prolog Facts, Questions & Rules Atoms & Variables

Next TimeNext Time

Terms & Proof ProceduresTerms & Proof Procedures Bratko, Chapter 2Bratko, Chapter 2