Database Manipulation Section 7.4. Prolog Knowledge Base n Knowledge base = database –set of facts/rules in the program n Can add/subtract facts and rules.

Slides:



Advertisements
Similar presentations
Artificial Intelligence: Natural Language and Prolog
Advertisements

CS4026 Formal Models of Computation Part II The Logic Model Lecture 6 – Arithmetic, fail and the cut.
© Patrick Blackburn, Johan Bos & Kristina Striegnitz Lecture 10: Cuts and Negation Theory –Explain how to control Prolog`s backtracking behaviour with.
Higher Order Predicates Higher order predicates in PROLOG. Higher order declarative predicates : – findall – bagof – setof – =.. Higher order non-declarative.
Constructing a prolog program We will learn predicates for: – input and output. – Modifying the knowledge base. – Controlling backtracking process.
Introduction to Recursion and Recursive Algorithms
Software Development Languages and Environments. Programming languages High level languages are problem orientated contain many English words are easier.
Introduction to PROLOG ME 409 Lab - 1. Introduction to PROLOG.
11/10/04 AIPP Lecture 6: Built-in Predicates1 Combining Lists & Built-in Predicates Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture.
LING 388: Language and Computers Sandiway Fong Lecture 5: 9/8.
1 Introduction to Prolog References: – – Bratko, I., Prolog Programming.
”assert” and ”retract”
Prolog OR (disjunction) “;” is same as a logical OR “;” is same as a logical OR It is also equivalent to using separate clauses... It is also equivalent.
Recursion. Recursion is a powerful technique for thinking about a process It can be used to simulate a loop, or for many other kinds of applications In.
For Monday Take home exam due Exam 1. For Wednesday Read chapter 10, sections 1-2 Prolog Handout 4.
CS 330 Programming Languages 12 / 02 / 2008 Instructor: Michael Eckmann.
MB: 2 March 2001CS360 Lecture 31 Programming in Logic: Prolog Prolog’s Declarative & Procedural Semantics Readings: Sections
Introduction to Prolog Proof Procedures. Exercise parent(mark, alex). parent(di, alex). brother(brian, mark). sister(cathy, di). wife(susan, brian). husband(brad,
CS 330 Programming Languages 12 / 12 / 2006 Instructor: Michael Eckmann.
For Friday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Controlling Backtracking Notes for Ch.5 of Bratko For CSCE 580 Sp03 Marco Valtorta.
Recursion. Binary search example postponed to end of lecture.
”assert” and ”retract”  Modifying Programs Dynamically  Prolog’s Execution Tree.
1 CILOG User Manual Bayesian Networks Seminar Sep 7th, 2006.
Mr Barton’s Maths Notes
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages – It’s elegant, minimal, can.
1 Software Development Topic 2 Software Development Languages and Environments.
FATIH UNIVERSITY Department of Computer Engineering Controlling Backtracking Notes for Ch.5 of Bratko For CENG 421 Fall03.
Introduction to Prolog Terms & Matching Math. Atoms and Terms n mark, alex, di, bob are atoms –Not variables –Not strings –Just things – simple things.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Nachos Phase 1 Code -Hints and Comments
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
14/10/04 AIPP Lecture 7: The Cut1 Controlling Backtracking: The Cut Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 7 14/10/04.
Flow of Control Chapter 5. Flow of Control n What order computer uses to get answers –sub-goal ordering –clause ordering n Prolog flow-of-control –sequence.
30/09/04 AIPP Lecture 3: Recursion, Structures, and Lists1 Recursion, Structures, and Lists Artificial Intelligence Programming in Prolog Lecturer: Tim.
F28PL1 Programming Languages Lecture 16: Prolog 1.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
15/11/04 AIPP Lecture 14: Database Manipulation1 Database Manipulation Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 14 15/11/04.
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.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
Introduction to Prolog Facts, Questions & Rules Atoms & Variables.
1 COMP 205 Introduction to Prolog Dr. Chunbo Chu Week 14.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
1 Prolog and Logic Languages Aaron Bloomfield CS 415 Fall 2005.
Prolog Program Style (ch. 8) Many style issues are applicable to any program in any language. Many style issues are applicable to any program in any language.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
PROGRAMMING LANGUAGES: PROLOG, CLOJURE, F# Jared Wheeler.
Negation Chapter 5. Stating Negative Conditions n Sometimes you want to say that some condition does not hold n Prolog allows this –not/1this is a predicate.
Lists in Prolog Sections 3.1, 3.2. Lists n List = sequence of values –[1, 2, 3, 4, 5] –[bob, brian, cathy, mark, david, loretta] –[birds(4, calling),
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Creating a GUI Class An example of class design using inheritance and interfaces.
For Monday Exam 1 is Monday Takehome due Prolog Handout 3 due.
In The Name Of Allah Lab 03 1Tahani Aldweesh. objectives Searching for the solution’s. Declaration. Query. Comments. Prolog Concepts. Unification. Disjunction.
For Friday No reading Prolog Handout 2. Homework.
1 Knowledge Based Systems (CM0377) Lecture 9 (Last modified 11th April 2002)
Prolog 3 Tests and Backtracking 1. Arithmetic Operators Operators for arithmetic and value comparisons are built-in to Prolog = always accessible / don’t.
07/10/04 AIPP Lecture 5: List Processing1 List Processing Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 5 07/10/04.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
1 TP #2: How does Prolog answer questions? n Miscellaneous info; n Last TP exercises solved; n How does Prolog answer questions? n Recursive Prolog programs;
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
Prolog Fundamentals. 2 Review Last Lecture A Prolog program consists of a database of facts and rules, and queries (questions). –Fact:.... –Rule:... :-....
For Friday No reading Prolog handout 3 Chapter 9, exercises 9-11.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now:
Tests, Backtracking, and Recursion
Programming Paradigms and Languages
Python programming exercise
Module 1-10: Recursion.
Presentation transcript:

Database Manipulation Section 7.4

Prolog Knowledge Base n Knowledge base = database –set of facts/rules in the program n Can add/subtract facts and rules at run time n Adding facts/rules –assert, asserta, assertz n Subtracting facts/rules –retract, retractall

Asserting a Fact n Just tell prolog that it’s so ?- raining. ERROR: Undefined procedure: raining/0 ?- assert(raining). Yes ?- raining. Yes n Prolog didn’t know about raining/0

Preparing Prolog for a Predicate n Need to tell Prolog that the predicate exists –helpful also to say that it may have rules added n Give a directive in the program file –a command to Prolog :- dynamic raining/0. n Says that raining/0 is a predicate –prevents the error message

Dynamic Predicates n Can be done during session ?- dynamic foggy/0. Yes ?- foggy. No n Note how we call goals in a file :- dynamic foggy/0. –can do that with any query

Asserting Rules n Just give rule instead of fact –use parentheses if rule is compound (to prevent confusion about the comma) ?- assert(raining). ?- assert(bad :- raining ; foggy). ?- assert(nice :- (sunshine, \+ cold)). ?- bad. Yes

Assertion Order n assert/1 puts the fact/rule in the database –order is implementation dependent –(SWI-Prolog puts it at the end) n asserta/1 puts fact/rule in front n assertz/1 puts fact/rule at end

Assertion Order ?- assert(num(1)). ?- assertz(num(2)). ?- asserta(num(0)). ?- assertz(num(3)). ?- num(X). X = 0 ; X = 1 ; X = 2 ; X = 3 Adds num(1) to database Adds num(2) to end of DB Adds num(0) to front of DB Adds num(3) to end of DB num(1). num(2). num(0). num(3).

Assertion Order Exercise ?- asserta(what(1)). ?- assertz(what(2)). ?- asserta(what(3)). ?- assertz(what(4)). ?- asserta(what(5)). ?- what(X). X = ? ;

Exercise n Write a predicate that asks the user for a person’s parents & asserts those facts ?- add_parents(mark). Who is mark’s father? bob. Who is mark’s mother? isabel. Yes ?- father(mark, Dad), mother(mark, Mom). Dad = bob, Mom = isabel

Solution ask_parents(Person) :- ask_for_who(Person, father, Dad), ask_for_who(Person, mother, Mom), assert(father(Person, Dad)), assert(mother(Person, Mom)). ask_for_who(Person, Role, Name) :- write(‘Who is ’), write(Person), write(‘\’s ’), write(Role), write(‘? ’), read(Name).

Retraction n Tell Prolog to remove a fact/rule ?- raining. Yes ?- retract(raining). Yes ?- raining. No

Retracting Rules n As for asserting rules –use parentheses if body is compound –body may be a variable/partly instantiated ?- retract(bad :- raining ; foggy). ?- retract(nice :- Body). Body = sunshine, \+ raining Yes

Retraction Order n From first to last ?- retract(num(N)), retract(num(M)). N = 0 M = 1 Yes n retract fails if no clause matches

Retracting All Clauses n rectractall/1 retracts multiple clauses –all clauses with head matching the argument ?- num(N). N = 0 ?- retractall(num(N)). Yes ?- num(N). No Note:also gets rules ?- assert(bad :- member(1,[1])). Yes ?- bad. Yes ?- retractall(bad). Yes ?- bad. No

Asserting and Retracting n Used for AI programs that learn –create a new rule & add it to the database –forget an old rule n Can also be used for efficiency –asserta solutions previously found –found before general code called

Naïve Fibonacci fib(1, 1). fib(2, 1). fib(N, F) :- N > 2, N1 is N – 1, fib(N1, F1), N2 is N – 2, fib(N2, F2), F is F1 + F2.

Trace fib(5,F) fib(5, F 0 ) fib(4, F 1 ) fib(3, F 2 ) fib(2, F 3 )  F 3 = 1 fib(1, F 4 )  F 4 = 1 fib(2, F 5 )  F 5 = 1 fib(3, F 2 ) fib(2, F 3 )  F 3 = 1 fib(1, F 4 )  F 4 = 1 fib(3, F) gets calculated again extra work done much worse as #s get bigger

Assertional Fibonacci (8.5.4) fib2(1, 1). fib2(2, 1). fib2(N, F) :- N > 2, N1 is N – 1, fib2(N1, F1), N2 is N – 2, fib2(N2, F2), F is F1 + F2, asserta( fib2(N, F) ).% remember the result % at the beginning

Trace fib2(5,F) fib2(5, F 0 ) fib2(4, F 1 ) fib2(3, F 2 ) fib2(2, F 3 )  F 3 = 1 fib2(1, F 4 )  F 4 = 1 asserta( fib2(3, 2) ) fib2(2, F 5 )  F 5 = 1 asserta( fib2(4, 3) ) fib2(3, F 6 )  F 6 = 2 asserta( fib2(5, 5) ) Saves work from calculating fib(3) Matches asserted fact – no need to recalculate

Problems for Asserting Solutions n Backtracking gives multiple solutions –saved solution found first –then solution re-calculated –and re-asserted: solution there twice, now –next time there’ll be three solutions n Adding a cut to the solution might help –asserta( fib2(F, N) :- ! ).

Generating Facts n Multiplication table make_table :- \+ (L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], member(X, L), member(Y, L), Z is X * Y, assert(product(X, Y, Z)), fail).

Using the Multiplication Table n Now have 100 multiplication facts ?- product(X, Y, 12). X = 2, Y = 6 ; X = 3, Y = 4 ; X = 4, Y = 3 ; X = 6, Y = 2 ; No

Asserts on Calls in Progress n Suppose assert or assertz a clause of a predicate that’s in progress –is that clause considered for that call? strange(N) :- assertz(strange(N)),fail. n Does strange(3) succeed or fail? –or throw an exception

Speed of Dynamic Predicates n Dynamic predicates may be slower than static (dynamic = can change, static = can’t) n Prolog may have a better way for remembering solutions –remember or record predicates to memorize –recall or recorded to recall –forget or erase to forget

Remembering Solutions n One clause (near front) to look for remembered solutions –cut if find one n Remember solution after it’s calculated

Remembering Fibonacci fib_mem(0, 1). fib_mem(1, 1). fib_mem(N, F) :- recorded(fibonacci, fib(N, F)), !. fib_mem(N, F) :- N > 1, succ(N1, N),fib_mem(N1, F1), succ(N2, N1),fib_mem(N2, F2), succ(N2, N1),fib_mem(N2, F2), F is F1 + F2,recorda(fibonacci, fib(N, F)). F is F1 + F2,recorda(fibonacci, fib(N, F)).

Recording n recorda/2, recordz/2 store 2 nd argument –use 1 st argument as a key –you can record same fact under multiple keys –key is integer or atom (or term – but no good) n recorded/2 retrieves fact –needs key – only retrieves facts under that key –matches fact – only those that match selected

Erasing/Forgetting n recorded/3 also gives a memory location n Can use the location to erase the record ?- recorded(fibonacci, fib(500,_), Mem), erase(Mem).Yes n Can only erase one item at a time –don’t erase anything more than once

Versions of Fibonacci n Vanilla version is very slow –and only works on a few numbers n Remembering version quite fast –even faster when asking a second time n Single recursion version very fast –but second time takes as long as first ?- time(fib(20, F)), time(fib2(20, F)), time(fib_mem(20, F)).

Looking at Code n Program can inspect its own code n clause/2 returns clauses of program –1 st argument is the head of the rule –2 nd argument is the body –at least one argument must be given

Clause/2 sibs(Sib1, Sib2) :-parent(Sib1, P), parent(Sib2, P), different(Sib1, Sib2). different(X, Y) :- X \= Y. ?- clause(sibs(_, _), Body). Body = parent(_1,_2), parent(_3,_2), different(_1,_3) ?- clause(Head, _A \= _B). Head = different(_1,_2) Note: this last one doesn’t seem to work in SWI-Prolog

Compound Bodies n Body is a term – a comma term ?- (a, b, c, d) = (X, Y). X = a Y = b, c, d n Needs to be in parentheses when 2 nd arg. ?- clause(sibs(_,_), (parent(_,_), _) ). Yes Is there a clause of sibs/2 with a body like parent(_,_), …

Bodies of Facts n Puts true/0 in for body of fact parent(mark, alex). parent(bob, mark). parent(X, brian) :- parent(X, mark). ?- clause(parent(X, Y), Body). X = mark, Y = alex, Body = true ; X = bob, Y = mark, Body = true ; X = _1, Y = brian, Body = parent(_1,mark)

Looking at Built-in Code n Some built-in predicates are available ?- clause(member(X,Y), Body). X = _1, Y = [_1|_2], Body = true ; X = _1, Y = [_2|_3], Body = member(_1, _3) n Others are hidden ?- clause(clause(A,B), Body). ERROR: No permission to access private_procedure `clause/2'

Modifying Code n Replace every rule of the form –H :- …, different(X,Y), … n with –H :- …, X \= Y, … n (where the other bits don’t change) n Maybe for efficiency –H should be specified (else errors ensue)

Method for Modifying Code n Find a rule with matching head –Note: predicate must be dynamic n If it has a different(X,Y) in it, –replace it with X \= Y –retract old rule –assert new rule

Modification Predicate modify_rule(Head, Old, New) :- clause(Head, Body), replace_code(Body, Old, New, NewBody), retract(Head :- Body), assert(Head :- NewBody). replace_code((Old,More), Old, New, (New,More)). replace_code((H,OldT), Old, New, (H,NewT)) :- replace_code(OldT, Old, New, NewT). replace_code(Old, Old, New, New).

Modifying Code ?- modify_rule(sib(_,_), different(X,Y), X\=Y). before: sib(A, B) :- parent(A,C),parent(B,C),different(A,B). n Problem – only modifies one clause! after: sib(A, B) :- parent(A,C),parent(B,C), A \= B.

Modifying All Clauses n Prolog prints bindings –ask for another solution –Prolog backs up to clause/2 & gets another rule –then changes that rule n Keep asking for answers until all done –it works – will stop when no rule has Old in it –it’s sort of like a loop

“Failure Driven Loops” n Need to make a change, then fail –Prolog will try another clause n Have predicate make a change, then fail –it will change all the rules before saying No n Says No even tho’ it worked! –if we put \+ in front, it’ll say Yes instead! –that’s more intuitive for user

Modify All modify_all(Head, Old, New) :- \+ modify_and_fail(Head, Old, New). modify_and_fail(Head, Old, New) :- modify_rule(Head, Old, New), fail. OR Just modify_all(Head, Old, New) :- \+ (modify_rule(Head, Old, New), fail).

Remaining Problem n too_different/3 is not fully changed –replace_code only changes first Old to New –backtracking doesn’t pick up new clause n Try to fix by making replace_code change all –unexpected side-effect: all X\=Y made the same –too_different(A,A,A) :- A\=A, A\=A, A\=A. n Too complicated for us!

Next Time n Definite Clause Grammars