Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

LOGIC Programming Rules

Uploaded by

darthvader3816
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

LOGIC Programming Rules

Uploaded by

darthvader3816
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Logic Programming

Logic
• Logic is not concerned with what is true. Logic is the study of what follows from
what. What conclusions follow from a set of premises.
• It can be defined as study of principles of correct reasoning.
• The main thing we study in logic are principles governing the validity of arguments
and check that whether certain conclusion follows from some given assumption.

• Consider:
Alice likes everyone who likes logic
Alice likes logic

Alice likes himself.

Is this argument valid? How do you know?


• The logic process takes in some information called premises and produces some
outputs called conclusions.
Introduction
Logic programming languages, sometimes called
declarative programming languages

Express programs in a form of symbolic logic

Use a logical inferencing process to produce results

Declarative rather that procedural:


Only specification of results are stated (not detailed procedures for producing
them)

1-3
Symbolic Logic
• Method of representing logical expressions
through the use of symbols and variables, rather
than in ordinary language.
• It provides the benefit of removing the ambiguity
that is generally seen in ordinary languages like
English.
• Its normally divided into two branches:
1. Propositional Logic
2. Predicate Logic
Propositional Logic
• Simplest form of formal logic.
• All statements made are called propositions.
• The FORMAL LOGIC is concerned with syntax of
statements and not with their semantics.
• It deals with manipulation of logical variables
which represents proposition.
• Propositional Logic is concerned with the subset of
declarative sentences that can be either true or
false.
• Propositional Logic takes only two values, either TRUE
or FALSE.
A proposition is basically a declarative sentence
that has a truth value. Truth value can either be
true or false, but it needs to be assigned any of
the two values and not be ambiguous.

The purpose of using propositional logic is to


analyze a statement, individually or
compositely.
Syntax of Propositional Logic
1. Letters A, B,….Z and these letters with subscripted
numerals are well-formed atomic propositions.
2. If A and B are well-formed propositions so are
1. ~A (Negation of A)
2. (A & B) (Conjunction of A with B)
3. (A V B) (Inclusive Disjunction of A with B)
4. (A 🡪 B) (A implies B)
5. (A↔ B) (Material biconditional of A with B)
6. (A B) (Exclusive Disjunction of A with B)
7. (A | B)(Joint Denial of A with B)
8. (A↓ B) (Disjoint Denial of A with B)
Semantics of Logical Propositions
Truth tables for Logical Connectives
A B ~A ~B A V B A & B A 🡪 B A ↔ B A B A|B A↓ B
T T F F T T T T F F F
F T T F T F T F T T F
T F F T T F F F T T F
F F T T F F T T F T T

Example:
Let A be a Proposition: The machine is
defective. Let B be a Proposition: The
production is less.
Why we use Propositional Logic?
• Its easier to check formulas.
• We can exploit the Boolean nature for
efficient reasoning.
• Its easier to incrementally add formulas.
• It can be extended infinitely to many variables
using logical quantifiers.
The following statements :

If x is real, then x2 > 0


What is your name?
(a+b)2 = 100
This statement is false.
This statement is true.

Are not propositions because they do not have a


truth value. They are ambiguous.
rules = [
Rule('{P} ⇒ {Q}', 'if {P} then {Q}', 'if {P}, {Q}'),
Rule('{P} ⋁ {Q}', 'either {P} or else {Q}', 'either {P} or {Q}'),
Rule('{P} ⋀ {Q}', 'both {P} and {Q}'),
Rule('~{P} ⋀ ~{Q}', 'neither {P} nor {Q}'),
Rule('~{A}{P} ⋀ ~{A}{Q}', '{A} neither {P} nor {Q}'), # The Kaiser neither ...
Rule('~{Q} ⇒ {P}', '{P} unless {Q}'),
Rule('{P} ⇒ {Q}', '{Q} provided that {P}', '{Q} whenever {P}',
'{P} implies {Q}', '{P} therefore {Q}',
'{Q}, if {P}', '{Q} if {P}', '{P} only if {Q}'),
Rule('{P} ⋀ {Q}', '{P} and {Q}', '{P} but {Q}'),
Rule('{P} ⋁ {Q}', '{P} or else {Q}', '{P} or {Q}'),
]

negations = [
(word("not"), ""),
(word("cannot"), "can"),
(word("can't"), "can"),
(word("won't"), "will"),
(word("ain't"), "is"),
("n't", ""), # matches as part of a word: didn't, couldn't, etc.
]
English: If you build it, he will come.

Logic: (P ⇒ Q)
P: you build it
Q: he will come

English: A ham sandwich is better than nothing and nothing is better than
eternal happiness therefore a ham sandwich is better than eternal happiness.

Logic: ((P ⋀ Q) ⇒ R)
P: A ham sandwich is better than nothing
Q: nothing is better than eternal happiness
R: a ham sandwich is better than eternal happiness

English: Either Danny didn't come to the party or Virgil didn't come to the
party.

Logic: (~P ⋁ ~Q)


P: Danny did come to the party
Q: Virgil did come to the party
Preposition Logic applications
Searches of things like the web, or large databases,
such as our library's catalog, often can be done using
logical operators.

Searches Google for pages containing "Mexico" and


"university" but not "New".

Propositional logic can be applied to the design of


computer hardware.
First-order Predicate Logic
• First-order predicate calculus (FOPL) was developed
by logicians to extend the expressiveness of
Propositional Logic.
• It is generalization of propositional logic that permits
reasoning about world entities (objects) as well as
classes and subclasses of objects.
• Prolog is also based on FOPL.
• Predicate logic uses variables and quantifiers which is
not present in propositional logic.
Why First-Order Predicate Logic ?
• Suppose we are having 2 statements , based on which
we have to draw a conclusion.

Statement 1: All students must take Java.


Statement 2: John is a student.

• According to human inference,


John must take Java.

but not according to Propositional logic. (Disadvantage)


First-Order Predicate Logic
• 0 is a natural number
Natural(0)
• For all x, if x is a natural number, then so is
successor of x
For all x, natural (x) 🡪 natural (successor(x))
• 2 is a natural number
Natural(2)
• -1 is a natural number
Natural(-1)
First-order predicate calculus
First-order predicate calculus classifies the
different parts of such statements as follows:
1. Constants
2. Predicates
3. Functions
4. Variables
5. Connectives
6. Quantifiers
7. Punctuation Symbols
Predicates
• These are names for functions that are true or false,
like Boolean functions in a program.
• Defined as a relation that binds two atoms together.
• Example: Amit likes sweets.
likes(amit, sweets).
amit and sweets are atoms; likes is a predicate
• Predicates can take a number of arguments.
• In Example , the predicate natural takes one
argument. natural(n).
Predicates
• Its possible to have a function as an argument
• Eg. Ravi’s father is Rani’s father
father(father(ravi), rani).
Father is a predicate and father(ravi) is a function to
indicate Ravi’s father.
a. Constants
• These are usually numbers or names.
• Sometimes they are called atoms, since
they cannot be broken down into subparts.
• Example
natural(0).
0 is a constant
b. Variables
• Stands for Quantities that are yet Unspecified.
• Example
valuable(X)
X is a variable.
c. Functions
• First-order predicate calculus distinguishes
between functions and predicates.
• Predicates - true or false and all other are
functions which represent non-Boolean values.
Quantifiers
• Declares the scope or range of variables in a logical
expression.
• Two basic quantifiers used in logic:
A. Universal Quantifier ( )
B. Existential quantifier (Ǝ)
• The statement:
For all x, natural(x) → natural(successor(x))
means that for every x in the universe, if x is a natural
number, then the successor of x is also a natural
number.
• A universal quantifier is used to state that a relationship
among predicates is true for all things in the universe named
by the variable x.
Quantifiers…
• If a is a variable, then is read as:
1. for all a
2. for each a
3. for every a
Quantifiers
• There is also the existential quantifier, there
exists (Ǝ), as in the following statement:
• there exists x, natural(x).
This statement means that there exists an x
such that x is a natural number.
• An existential quantifier is used to state that a
predicate is true of at least one thing in the
universe, indicated by the variable x.
Quantifiers…
• If b is a variable, then Ǝ is read as:
1. there exists a b
2. for some b
3. for atleast one b
1. All cats are mammals
- ∀X(cat(X)⇒mammal(X))
2. All of Bill’s kids are also Hillary’s kids
- ∀X(father(bill, X)⇒mother(hillary, X))
3. Somebody likes brain
- ∃X(likes(X,
brain))
4. Nobody likes brain
- ¬ ∃X[likes(X, brain)] or ∀X[¬ X(like(X,
brain))
Some points to remember
• Arguments to predicates and functions can
only be terms which is a combination of
variables, constants and functions.
• Terms cannot contain predicates, quantifiers or
connectives.
What is Prolog?
• Prolog is the most widely used language to have
been inspired by logic programming research.
• It is a declarative language.
• Prolog is computer programming language, used
for solving problems that involves objects and
relationships between objects.
• A Prolog program can also be seen as a relational
database containing rules as well as facts.
Structure of Logic Programs
• Programs consist of procedures.
• Procedures consist of clauses. Clauses are statements about what
is true about a problem, instead of instructions how to
accomplish the solution.
• Each clause is a fact or a rule.
• Programs are executed by posing queries.
• The Prolog system uses the clauses to work out how to
accomplish the solution by searching through the space
of possible solutions.
• Computer Programming in Prolog consists of:
– Declaring some facts about objects and their relationships.
– Declaring some rules about objects and their relationships.
– Asking questions (goals) about objects and their
relationships.
Why Rules?
• Rule is an extension of fact with added conditions that
have to be specified for it to be true.
• Rule is much more compact than a list of facts.
• When facts depend on a group of other facts.
• Example: John likes all people who likes sweets.
Way 1: Write down separate facts as below –
likes(james, sweets).
likes(john, james).
likes(john, joe).
likes(john, david).
….. So on
Rules…
Way 2: John likes any object provided it is a
person. In Prolog,
likes(john, X) :- like(X, sweets).

Head Body

If
Example
To write a rule, X is a sister of Y
• X is a female.
• X has mother M and father F and
• Y has the same mother and father as X does.
sister_of(X, Y) :-
female(X),
parents(X, M, F),
parents(Y, M, F).
Example
• To define a rule “X is a grandfather of Y, if X is a
father of Z and Z is a parent of Y ” using logic
programming convention, then we write
grandfather(X, Y) :- father(X, Z) , parent(Z, Y).

• X is a sibling of Y if they both have the same


parent.
sibling(X, Y) :- parent(Z, X) , parent(Z, Y).
Types of Query

1. In Ground query , the goal(s) contains


constants. Answer to ground query is either yes
or no depending upon whether it is a logical
consequence of a logic program or not.
2. In Non – Ground query, the goal(s)
should have at least one variable as an
argument.
Simple Queries
a. Ground Query:
“Is raman a grandfather of manu ?”
?- grandfather(raman, manu).
b. Non ground:
“Does there exist X such that X is a father of
manu ?” {Who is father of manu?}
?- father(X, robert).
Conjunctive Queries
a. Ground Query
“Is raman father of robert and robert is a
father of mike?
?- father(raman, robert), father(robert, mike).
Answer: yes
b. Non Ground Query
?- father(raman, X), father(X, mike).
Answer: X = robert
Inference Rule
• Ways of deriving or proving new statements
from a given set of statements.
• Example
a🡪 b, b 🡪 c
We can derive a 🡪 c
Horn Clauses
• Horn clause (named after its inventor Alfred Horn) is a
statement of the form:
a1 and a2 and a3 . . . and an → b
where the ai are only allowed to be simple statements involving no
connectives.
• Thus, there are no or connectives and no quantifiers in Horn clauses.
• b is called the head of the clause, and the a1 . . . , an is the body of
• the clause.
• In the Horn clause, the number of ai’s may be 0, in which case the
Horn clause has the form:
→b
• Such a clause means that b is always true. In other words, b is an
axiom and is usually written without the connective →. Such clauses
are sometimes also called facts.
Example
Consider the following statement:
x is a grandparent of y if x is the parent of someone
who is the parent of y.
Translating this into predicate calculus, we get
grandparent (x, y) for all x, for all y, (there exists
z, parent(x, z) and parent(z, y)).
As a Horn clause this is expressed simply as:
grandparent(x, y) parent(x, z) and parent(z, y) .
Example
Consider the following statement:
For all x, if x is a mammal then x has two or four
legs.
Translating in predicate calculus, we get:
for all x, mammal(x) → legs(x, 2) or legs(x, 4).
This may be approximated by the following Horn
clauses:
mammal(x) and not legs(x, 2) → legs(x, 4).
mammal(x) and not legs(x, 4) → legs(x, 2).
Examples written in Pred. Calc.:
Ancestors:
For all X and Y, parent(X,Y) → ancestor(X,Y).
For all A, B, and C, ancestor(A,B) and ancestor(B,C) →
ancestor(A,C).
For all X and Y, mother(X,Y) → parent(X,Y).
For all X and Y, father(X,Y) → parent(X,Y).
Father(Bill,Jill).
Mother(Jill,Sam).
Father(Bob,Sam).
Factorials:
Factorial(0,1).
For all n and m, factorial(n-1,m) → factorial(n,n*m).

Chapter 12 K. Louden, Programming Languages 42


Horn Clauses
Drop the quantifiers (i.e., assume them implicitly).
Distinguish variables from constants, predicates, and
functions by upper/lower case:
parent(X,Y) → ancestor(X,Y).
ancestor(A,B) and ancestor(B,C) → ancestor(A,C).
mother(X,Y) → parent(X,Y).
father(X,Y) → parent(X,Y).
father(bill,jill).
mother(jill,sam).
father(bob,sam).
factorial(0,1).
factorial(N-1,M) → factorial(N,N*M).

Chapter 12 K. Louden, Programming Languages 43


Prolog
Modified Horn clause syntax: write the clauses backward, with
:- as the (backward) arrow, comma as "and" and semicolon as
"or":
ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :-
ancestor(X,Z), ancestor(Z,Y).
parent(X,Y) :- mother(X,Y).
parent(X,Y) :- father(X,Y).
father(bill,jill).
mother(jill,sam).
father(bob,sam).
factorial(0,1).
factorial(N,N*M) :- factorial(N-1,M).

Chapter 12 K. Louden, Programming Languages 44


Unfortunate Errors:
?- ancestor(bill,sam).
Yes.
?- ancestor(bill,X).
X = jill ;
X = sam ;
ERROR: Out of local stack
?- ancestor(X,bob).
ERROR: Out of local stack
?- factorial(2,2).
No
?- factorial(0,X).
X = 1 ;
ERROR: Out of global stack

Chapter 12 K. Louden, Programming Languages 45


What's Wrong????
Immediat
ancestor(X,Y) :- parent(X,Y). e
ancestor(X,Y) :- recursion
ancestor(X,Z), ancestor(Z,Y).
parent(X,Y) :- mother(X,Y).
parent(X,Y) :- father(X,Y).
father(bill,jill).
mother(jill,sam). No arithmetic is
father(bob,sam). actually
factorial(0,1). computed
factorial(N,N*M) :- factorial(N-1,M).

Chapter 12 K. Louden, Programming Languages 46


Arithmetic
Easy to fix - arithmetic expressions must be explicitly
forced:
?- 2*3 = 6. "is" forces its
No right-hand argument
?- 2*3 = 2*3.
Yes But not its left-hand
?- 6 is 2*3. argument
Yes
?- 2*3 is 6.
No
Rewrite factorial like this:
factorial(0,1).
factorial(N,P) :- N1 is N-1,
factorial(N1,M), P is M*N.
Chapter 12 K. Louden, Programming Languages 47
Stack Problems a bit harder:
Stack problems still exist for factorial:
?- factorial(7,X).
X = 5040 ;
ERROR: Out of local stack
To figure this out, we must understand the procedural
interpretation of Horn clauses:
a :- b, c, d.
represents the definition of a (boolean) function
named a. The body of a is given by the clauses on the
right hand side: b, then c, then d.
Note similarity to recursive-descent parsing! Also
note sequencing!

Chapter 12 K. Louden, Programming Languages 48


Prolog's Execution Strategy
Given a query or goal, Prolog tries to pattern match the
goal with the left-hand sides of all clauses, in a
sequential top-down fashion.
Any lhs that matches causes the rhs terms to be set up
sequentially as subgoals, which Prolog immediately
tries to match in turn with lhs terms.
Thus, Prolog's execution path is top-down, left-to-right,
depth-first. All intermediate results are kept for
backtracking purposes.

Chapter 12 K. Louden, Programming Languages 49


Solving the stack problems

For the ancestor problem, just remove the left


recursion:
ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :-
ancestor(X,Z), ancestor(Z,Y).
parent(X,Z)
● For the factorial problem, it involves
preventing reuse of the recursive rule:
factorial(0,1).
factorial(N,P) :- not(N=0), N1 is N-1,
factorial(N1,M), P is M*N.

Chapter 12 K. Louden, Programming Languages 50


Lists
Prolog uses almost the same list syntax as Haskell or
ML: [1,2,3]
Head and tail pattern syntax is different:
[H|T] versus (h:t) in Haskell or (h::t) in ML
Also, as many elements as desired can be written
using commas before the bar:
[1,2,3|[4]] is the list [1,2,3,4].
Example:
?- [1,2,3] = [X,Y|_].
X = 1
Y = 2

Chapter 12 K. Louden, Programming Languages 51


Pattern Matching
Pattern matching is more general in Prolog than it is
in Haskell:
variables can be repeated in patterns, implying that they must be the same value:
?- [1,1] = [X,X].
X = 1
?- [1,2] = [X,X].
No
Other operations can be more general too.

Chapter 12 K. Louden, Programming Languages 52


Final Examples
The append list operation:
append([],X,X).
append([H|T],L,[H|M]) :-
append(T,L,M).
Quicksort:
quicksort([],[]).
quicksort([H|T],Result) :-
split(H,T,A,B),/* exercise */
quicksort(A,X),
quicksort(B,Y),
append(X,[H|Y],Result).
Chapter 12 K. Louden, Programming Languages 53
Resolution
• Resolution says that if we have two Horn clauses,
and we can match the head of the first Horn
clause with one of the statements in the body of
the second clause, then the first clause can be used
to replace its head in the second clause by its
body.
In symbols, if we have Horn clauses:
a ← a1, . . . , an.
b ← b1, . . . , bm.
and bi matches a, then we can infer the clause:
b ← b1, . . . , bi-1, a1, . . . , an, bi+1, . . . , bm.
• The system attempts to apply resolution by matching one of
the goals in the body of the headless clause with the head of
a known clause. It then replaces the matched goal with the
body of that clause, creating a new list of goals, which it
continues to modify in the same way. The new goals are
called subgoals.
• If the system succeeds eventually in eliminating all goals—
thus deriving the empty Horn clause—then the original
statement has been proved.
• In symbols, if we have the goal: ← a.
• and the clause a ← a1, . . . , an, then resolution replaces the
original goal a with the subgoals:
← a1, . . . , an.
Unification
• To match statements that contain variables, we must set
the variables equal to terms so that the statements
become identical and can be canceled from both sides.
This process of pattern matching to make statements
identical is called unification, and variables that are
set equal to patterns are said to be instantiated.
• Unification is the process by which variables are
instantiated, or allocated memory and assigned values,
so that patterns match during resolution. It is also the
process of making two terms the same in some sense.
• The built in Prolog operator '=' can be used to unify two
terms.
Examples
?- me = me.
yes
?- me =
you. no
?- me = X.
X = me
?- f(a, X) = f(Y, b).
X=b
Y=a
?- f(X) = g(X).
no
?- f(X) = f(a, b).
no
?- f(a, g(X)) = f(Y, b).
no
?- f(a, g(X)) = f(Y, g(b)).
X=b
Y=a
Unification algorithm for Prolog
1. A constant unifies only with itself: me = me succeeds but me = you fails.
2. A variable that is uninstantiated unifies with anything and becomes instantiated
to that thing.
3. A structured term (i.e., a function applied to arguments) unifies with another term only if
it has the same function name and the same number of arguments, and the arguments
can be unified recursively.
Thus, f(a, X) unifies with
f(Y, b) by instantiating X to b and Y to a.

A variation on case 2 is when two uninstantiated variables are unified:


?- X =
Y. X =
_23 Y =
_23
The number printed on the right-hand side—in this case, indicates an internal memory
location set aside for that variable. Thus, unification causes uninstantiated
variables to share memory—that is, to become aliases of each other.
Example
Given the rules and facts:
legs(x, 2) ← mammal(x), arms(x, 2).
legs(x, 4) ← mammal(x), arms(x, 0).
mammal(horse).
arms(horse, 0).
if we supply the query:
← legs(horse,4).
We get X= horse as output
Example
For example, given the Horn clauses:
ancestor(x, y) ← parent(x, z), ancestor(z, y).
ancestor(x, x).
parent(amy, bob).
if we provide the query:
← ancestor(x, bob).

We get X = bob , X = amy


Prolog Arithmetic
?- write(3 + 5).
3+5
To force the evaluation of an arithmetic term, a new operation is required: the built-
in predicate is.
?- X is 3 + 5, write(X).
X=8
?- 3 + 4 = 4 + 3.
no
To get equality of values, we must force evaluation using is, for example, by
writing the predicate:
valequal(Term1, Term2) :-
X is Term1, Y is Term2, X = Y.

We would then get:


?- valequal(3 + 4, 4 + 3).
yes
Example
?- foo(a,Y) = foo(X,b).
** Instantiation of variables may occur in either of
the terms to be unified **
Y=b
X=a yes
Example
?- foo(a,b) = foo(X,X).
** In this case there is no unification because foo(X,X)
must have the same 1st and 2nd arguments **

no
Example
?- 2*3+4 = X+Y.
** The term 2*3+4 has principal functor +
X=2*3 and therefore unifies X+Y with X
instantiated to 2*3 and Y instantiated to 4 **

yes
Example
?- [a,b,c] = [X,Y,Z].
** Lists unify just like other terms
** X=a Y=b Z=c
yes
Example
Do the following pairs of items unify (match) ?
eats(fred,tomatoes)
eats(WHOM,WHAT)
Yes WHOM = fred and WHAT = tomatoes.
Example
cd(29,beatles,sgt_pepper).
cd(A,B,help).
No sgt_pepper and help do not unify

f(X,Y)

f(P,P)
Yes X = P and Y = P. A variable (such as X) can be
bound to another variable (such as P). In this case
we can also infer that X = Y
Example
f(X,a)
f(a,X)
Yes X = a
Example
likes(jane,X)
likes(X,jim)
No X can not be bound to both jane and jim

f(foo,L)
f(A,A)
Yes A = foo and A = L. Hence L = foo
A and L are variables

You might also like