# Mrinalini Rana

CSE7th sem

685034228

(Submitted in the partial fulfillment of B.TECH) S.B.B.S.I.E.T (Affiliated to PTU)

Submitted To: Lect.Gurpreet Singh

Submitted By:Mrinalini Rana 685034228 CSE (7th sem)

S.B.B.S.I.E.T

1

Mrinalini Rana

CSE7th sem

685034228

PRACTICAL NO.1:

Aim: Study of propositional logic.

In logic and mathematics, a propositional calculus or logic (also a sentential calculus) is a formal system in which formulae representing propositions can be formed by combining atomic propositions using logical connectives, and a system of formal proof rules allows certain formulae to be established as theorems. Propositional logic, also known as sentential logic and statement logic, is the branch of logic that studies ways of joining and/or modifying entire propositions, statements or sentences to form more complicated propositions, statements or sentences, as well as the logical relationships and properties that are derived from these methods of combining or altering statements. In propositional logic, the simplest statements are considered as indivisible units, and hence, propositional logic does not study those logical properties and relations that depend upon parts of statements that are not themselves statements on their own, such as the subject and predicate of a statement. The most thoroughly researched branch of propositional logic is classical truth-functional propositional logic, which studies logical operators and connectives that are used to produce complex statements whose truth-value depends entirely on the truth-values of the simpler statements making them up, and in which it is assumed that every statement is either true or false and not both. However, there are other forms of propositional logic in which other truth-values are considered, or in which there is consideration of connectives that are used to produce statements whose truth-values depend not simply on the truth-values of the parts, but additional things such as their necessity, possibility or relatedness to one another.

Introduction:

A statement can be defined as a declarative sentence, or part of a sentence, that is capable of having a truth-value, such as being true or false. So, for example, the following are statements:

• • •

George W. Bush is the 43rd President of the United States. Paris is the capital of France. Everyone born on Monday has purple hair.

Sometimes, a statement can contain one or more other statements as parts. Consider for example, the following statement:

•

Either Ganymede is a moon of Jupiter or Ganymede is a moon of Saturn.

S.B.B.S.I.E.T

2

Mrinalini Rana

CSE7th sem

685034228

Joining two simpler propositions with the word “and” is one common way of combining statements. When two statements are joined together with “and”, the complex statement formed by them is true if and only if both the component statements are true. Because of this, an argument of the following form is logically valid: Paris is the capital of France and Paris has a population of over two million. Therefore, Paris has a population of over two million.

**The Language of Propositional Logic:
**

The basic rules and principles of classical truth-functional propositional logic are, among contemporary logicians, almost entirely agreed upon, and capable of being stated in a definitive way. This is most easily done if we utilize a simplified logical language that deals only with simple statements considered as indivisible units as well as complex statements joined together by means of truth-functional connectives. We first consider a language called PL for “Propositional Logic”. Later we shall consider two even simpler languages, PL’ and PL”.

**a. Syntax and Formation Rules of PL
**

In any ordinary language, a statement would never consist of a single word, but would always at the very least consist of a noun or pronoun along with a verb. However, because propositional logic does not consider smaller parts of statements, and treats simple statements as indivisible wholes, the language PL uses uppercase letters ‘A’, ‘B’, ‘C’, etc., in place of complete statements. The logical signs ‘&’, ‘v‘, ‘→’, ‘↔’, and ‘¬’ are used in place of the truth-functional operators, “and”, “or”, “if… then…”, “if and only if”, and “not”, respectively. So, consider again the following example argument, mentioned in Section I. Paris is the capital of France and Paris has a population of over two million. Therefore, Paris has a population of over two million. Definition: A well-formed formula (hereafter abbreviated as wff) of PL is defined recursively as follows: 1. 2. 3. 4. 5. 6. 7. Any statement letter is a well-formed formula. If α is a well-formed formula, then so is ¬α . If α and β are well-formed formulas, then so is (α & β) . If α and β are well-formed formulas, then so is (α v β) . If α and β are well-formed formulas, then so is (α → β) . If α and β are well-formed formulas, then so is (α ↔ β) . Nothing that cannot be constructed by successive steps of (1)-(6) is a well-formed formula.

S.B.B.S.I.E.T

3

and is false only if both α and β are false. ‘Q’ and ‘R’. in effect.B. In effect. A chart similar to that given above for conjunction. When setting up a language fully. is true if either α is true or β is true. This truth-function generates the following chart: α T T F β T F T (α → β) T F T
S. A statement of the form (α → β) .. Truth Functions and Truth Tables
So far we have in effect described the grammar of language PL.B.Mrinalini Rana
CSE7th sem
685034228
b. however. it is necessary not only to establish rules of grammar.T
4
. etc.E. is false if α is true and β is false. written in PL as (α & β) . or both α and β are true. and only considers those ways of combining them to form more complicated statements that make the truth or falsity of the whole dependent entirely on the truth or falsity of the parts. provided that each is taken as either true or false (and not both). the meaning of the operator ‘&’ can be displayed according to the following chart. We have already suggested that uppercase letters are used as complete simple statements. is true if both α and β are true.I. and is true if either α is false or β is true (or both). modified for to show the meaning of the disjunction sign ‘v‘ instead. and is false if either α is false or β is false or both are false. but also describe the meanings of the symbols used in the language. which shows the truth-value of the conjunction depending on the four possibilities of the truth-values of the parts: α T T F F β T F T F (α & β) T F F F
Disjunction: The disjunction of two statements α and β. would be drawn as follows: α T T F F β T F T F (α v β) T T T F
Material Implication: This truth-function is represented in language PL with the sign ‘→’. Conjunction: The conjunction of two statements α and β. it does not matter what meaning we assign to the individual statement letters like ‘P’.S. written in PL as (α v β) . Because truth-functional propositional logic does not analyze the parts of simple statements.

Rules of Inference
Here we give a list of intuitively valid rules of inference. negation is applied to a single statement. A statement of the form (α ↔ β) is regarded as true if α and β are either both true or both false.E.B. The corresponding chart can therefore be drawn more simply as follows: α T F ¬α F T
c. Modus ponens (MP): α→β α β (Modus ponens is sometimes also called “modus ponendo ponens”. Any inference in which any wff of language PL is substituted unformly for the schematic letters in the forms below constitutes an instance of the rule. is regarded as true if α is false. and is regarded as false if they have different truth-values. Unlike the other operators we have considered.B.S. and false if α is true. simply written ¬α in language PL.) Modus tollens (MT): α→β ¬β ¬α
S.I.T
5
. we have the following chart: α T T F F β T F T F (α ↔ β) T F F T
Negation: The negation of statement α. “detachment” or a form of “→-elimination”. The rules are stated in schematic form.Mrinalini Rana F F T
CSE7th sem
685034228
Material Equivalence: This truth-function is represented in language PL with the sign ‘↔’. Hence.

The result is that each term is assigned an object that it represents.B. The study of the interpretations of formal languages is called formal semantics. Semantics
An interpretation of a first-order language assigns a denotation to all non-logical constants in that language. and each sentence is assigned a truth value.I.E.S. In this way.T
6
.
S. It also determines a domain of discourse that specifies the range of the quantifiers.B.Mrinalini Rana
CSE7th sem
685034228
(Modus tollens is sometimes also called “modus tollendo tollens” or a form of “→elimination”. an interpretation provides semantic meaning to the terms and formulas of the language.)
d.

B. to the conclusion
Quantifiers:
•Universal
quantification corresponds to conjunction ("and") in that (Ax)P(x) means that P holds for all values of x in the domain associated with that variable. An elementary class is the set of all structures satisfying a particular theory. These classes are a main subject of study in model theory.g. and predicate logic. if elementary. The set of axioms is often finite or recursively enumerable. in which case the theory is called effective.
First-order logic is a formal logic used in mathematics.E.There are many deductive systems for first-order logic that are sound (only deriving correct results) and complete (able to derive any logically valid implication). each interpretation of first-order logic includes a domain of discourse over which the quantifiers range. linguistics..B. A first-order structure that satisfies all sentences in a given theory is said to be a model of the theory. Although the logical consequence relation is only semidecidable. philosophy. First-order logic is distinguished from propositional logic by its use of quantifiers. example of what can be done with the predicate logic is the inference from the premises:
• •
All men are mortal.T
7
.I. It goes by many names. Some authors require theories to also include all logical consequences of the axioms. A first-order theory consists of a set of axioms in a particular first-order signature. Socrates is a man. much progress has been made in automated theorem proving in first-order logic. –E. A classic. the lower predicate calculus. (Ax) dolphin(x) => mammal(x) •
S.2:
Aim: Study of First Order Predicate Logic.Mrinalini Rana
CSE7th sem
685034228
PRACTICAL NO. and computer science. including: first-order predicate calculus. First-order logic permits reasoning about the propositional connectives (as in propositional logic) and also about quantification ("all" or "some").S.

x and f(x1. or.g.y) –Someone is liked by everyone: (Ey)(Ax)likes(x.g.Mrinalini Rana
CSE7th sem
685034228
•Existential quantification corresponds to disjunction ("or") in that (Ex)P(x) means that P holds for some value of x in the domain associated with that variable.S. then (Ax)P and (Ex)P are sentences –A well-formed formula (wff) is a sentence containing no "free" variables. –An atom (which has value true or false) is either an n-place predicate of n terms.I.." –You rarely use universal quantification to make blanket statements about every individual in the world: (Ax)cs15-381-student(x) ^ smart(x) meaning that everyone in the world is a cs15-381 student and is smart.
Translating English to FOL:
•Every gardener likes the sun. P <=> Q are atoms –A sentence is an atom." –E. if P is a sentence and x is a variable. if P and Q are atoms. Similarly..T 8
.e. a variable symbol. –E. –E. where each xi is a term..g.B. •E. or a function e. • •Switching the order of universals and existentials does change meaning: –Everyone likes someone: (Ax)(Ey)likes(x.E. you can switch the order of existential quantifiers. (Ax) gardener(x) => likes(x. P ^ Q. For example. (Ax)P(x. (Ax) cs15-381-student(x) => smart(x) means "All cs15-381 students are smart.. (Ex) mammal(x) ^ lays-eggs(x) • •Universal quantifiers are usually used with "implies" to form "if-then rules.y) is logically equivalent to (Ay)(Ax)P(x. xn) are terms. I. P => Q..Sun)
S. .." –A common mistake is to represent this English sentence as the FOL sentence: (Ex) cs15381-student(x) => smart(x) • •Switching the order of universal quantifiers does not change the meaning: (Ax) (Ay)P(x. or. but y is free. (Ex) cs15-381-student(x) ^ smart(x) means "there is a cs15-381 student who is smart..B.g.y)
First-Order Logic (FOL) Syntax:
•Sentences are built up of terms and atoms:
–A term (denoting a real-world object) is a constant symbol. all variables are "bound" by universal or existential quantifiers..y). P V Q.y) has x bound as a universally quantified variable.g. left-leg-of ( ). •Existential quantifiers are usually used with "and" to specify a list of properties or facts about an individual. then ~P.

equivalently. (Ax)(Et) (person(x) ^ time(t) => canfool(x. x) we can infer eats(Ziggy. (Ex)(Ey) mushroom(x) ^ purple(x) ^ mushroom(y) ^ purple(y) ^ ~(x=y) ^ (Az) (mushroom(z) ^ purple(z)) => ((x=z) v (y=z)) • •Deb is not tall. (Ax)(Ay) above(x. For example. from eats(Ziggy.y) v (Ez) (on(x. IceCream) we can infer (Ex)eats(Ziggy. then (Ex)P(x) is inferred.Mrinalini Rana
CSE7th sem
685034228
• •You can fool some of the people all of the time. And-Elimination. Modus Ponens. (Ax) (mushroom(x) ^ purple(x)) => ~poisonous(x) • •There are exactly two purple mushrooms. In other words. –ExistentialElimination From (Ex)P(x) infer P(c).t) • •You can fool all of the people some of the time. Note that the variable symbol cannot already exist anywhere in the expression.B.B. •Note that the variable is replaced by a brand new constant that does not occur in this or any other sentence in the Knowledge Base. x) infer eats(Ziggy. For example. where c is a constant in the domain of x. from (Ex)eats(Ziggy. Cheese). ~(Ex) purple(x) ^ mushroom(x) ^ poisonous(x) or. •For example. i. •The variable symbol can be replaced by any ground term.y))) Inference Rules for FOL:
•Inference
rules for PL apply to FOL as well. then P(c) is true.y) <=> (on(x.I.z) ^ above(z. etc.S.E. AndIntroduction. ~tall(Deb) • •X is above Y if X is on directly on top of Y or else there is a pile of one or more other objects directly on top of one another starting with X and ending with Y. any constant symbol or function symbol applied to ground terms only. •New sound inference rules for use with quantifiers: –UniversalElimination If (Ax)P(x) is true.e.t) • •All purple mushrooms are poisonous. we don't want to accidentally S. (Ex)(At) (person(x) ^ time(t)) => canfool(x. •All instances of the given constant symbol are replaced by the new variable symbol.. x). •For example. from (Ax)eats(Ziggy. (Ax) (mushroom(x) ^ purple(x)) => poisonous(x) •No purple mushroom is poisonous. IceCream).T 9
. –ExistentialIntroduction If P(c) is true.

B. Intuitively. such as y = x. The truth value of this formula changes depending on whether x and y denote the same individual. The reason that a variable assignment is required is to give meanings to formulas with free variables. so we can introduce a brand new one to stand in for that (unknown) constant. Given terms that have been evaluated to elements of the domain of discourse. the term evaluates to . the variable assignment μ can be extended to all terms of the language. The domain of discourse D is a nonempty set of "objects" of some kind. The domain of discourse is the set of considered objects.T
10
. and a n-ary function symbol f.
Evaluation of truth values:
A formula evaluates to true or false given an interpretation. a first-order formula is a statement about these objects. and a variable assignment μ that associates an element of the domain of discourse with each variable.I. The result is that each term is assigned an object that it represents. Functions. In this way.B. one can take D to be the set of integer numbers. which by
S. for example. All we know is there must be some constant that makes this true.
Next.E. where are the and I(P) is the interpretation of P. It also determines a domain of discourse that specifies the range of the quantifiers. and each sentence is assigned a truth value.
Semantics:
An interpretation of a first-order language assigns a denotation to all non-logical constants in that language. states the existence of an object x such that the predicate P is true where referred to it. Atomic formulas (1). an interpretation provides semantic meaning to the terms and formulas of the language. with the result that each term maps to a single element of the domain of discourse. is associated the value true or . The study of the interpretations of formal languages is called formal semantics. each formula is assigned a truth value. For example. Each variable x evaluates to μ(x) 2. A formula false depending on whether evaluation of the terms assumption is a subset of Dn. 1. First. The inductive definition used to make this assignment is called the T-schema. Variables.Mrinalini Rana
CSE7th sem
685034228
draw other inferences about it by introducing the constant. The following rules are used to make this assignment: 1.S.

This formal definition captures the idea that is true if and only if there is a way to choose a value for x such that φ(x) is satisfied. as follows: 1.B. A formula is true according to M if. Universal quantifiers (alternate). A formula is true according to M and μ if φ(x) is true for every pair composed by the interpretation M and some variable assignment μ' that differs from μ only on the value of x. Existential quantifiers (alternate).
S. Instead. one first adds to the signature a collection of constant symbols. In other words. as in propositional logic. This alternate approach gives exactly the same truth values to all sentences as the approach via variable assignments. Here φ(cd) is the result of substituting cd for every free occurrence of x in φ. Atomic formulas (2).T
11
. 2. then the initial variable assignment does not affect its truth value. One now defines truth for quantified formulas syntactically. Universal quantifiers. 3. a sentence is true according to M and μ if and only if is true according to M and any other variable assignment μ'. is evaluated according to the truth table for the connective in question. and so is a sentence. 5. say that for each d in the domain the constant symbol cd is fixed.B. A formula is true according to M if there is some d in the domain of discourse such that φ(cd) holds. one for each element of the domain of discourse in M.I. A formula t1 = t2 is assigned true if t1 and t2 evaluate to the same object of the domain of discourse (see the section on equality below). There is a second common approach to defining truth values that does not rely on variable assignment functions. Existential quantifiers. A formula is true according to M and μ if there exists an evaluation μ' of the variables that only differs from μ regarding the evaluation of x and such that φ is true according to the interpretation M and the variable assignment μ'. The interpretation is extended so that each new constant symbol is assigned to its corresponding element of the domain. 4.Mrinalini Rana
CSE7th sem
685034228
2. φ(cd) is true according to M. A formula in the form . If a formula does not contain free variables.E. Logical connectives. given an interpretation M.S. for every d in the domain of discourse. etc. This captures the idea that is true if every possible choice of a value for x causes φ(x) to be true. .

and execution is triggered by running queries over these relations. and language parsing applications.1 AIM: Introduction to PROLOG programming. Given a query. called "pure Prolog".S. If the negated query can be refuted.B.E.
Prolog is a logic programming general purpose fifth generation language associated with artificial intelligence and computational linguistics. symbolic mathematics. Because Prolog allows impure predicates. checking the truth value of certain special predicates may have some deliberate side effect. Prolog is declarative: The program logic is expressed in terms of relations. is a logical consequence of the program. with the found instantiation applied. It has a purely logical subset.Mrinalini Rana
CSE7th sem
685034228
PRACTICAL NO. it follows that the original query.. Relations are defined by clauses. Relations and queries are constructed using Prolog's single data type.3:
3.e.T
12
. an instantiation for all free variables is found that makes the union of clauses and the singleton set consisting of the negated query false. such as printing a value to the
S. the Prolog engine attempts to find a resolution refutation of the negated query. as well as a number of extralogical features. the term. Prolog has its roots in formal logic.B. This makes Prolog (and other logic programming languages) particularly useful for database.I. and unlike many other programming languages. i.

Mrinalini Rana
CSE7th sem
685034228
screen. When you have done this you can use all the facts and rules that are contained in the program. In Prolog you don't say how the program will work.I. This mode is represented by the sign? . Now let's begin to see what a fact. When the file of your program is file. for this report we used the SWIProlog wich is a freeware (if you want to know more about SWI-Prolog go to this page).E.pl.B. For SWI-Prolog you can load a program by typing the cammand [file].
The Query
When you launch a program you are in query modequery mode. In query mode you ask questions about relations described in the program.At the begining of the line. Prolog can be separated in two parts:
The Program
The program. When Prolog is launched the? .
Loading a program:
Loading First you have to launch your Prolog compiler.pl) that contain the facts and rules that will be used by the user of the program.B. sometimes called Database is a texte file (*.
What is a Prolog program?
Programming in Prolog is very different from programming in a traditional proceduralprocedural language like Pascal.S.should appear meaning you are in query mode. It contains all the relations that make this program. The manier to launch a program depends of your compiler.is
S.. This permits the programmer to use some amount of conventional imperative programming when the logical paradigm is inconvenient. If you compiler is not SWI-Prolog you can also try the command reconsult(file).T
13
..

Facts either consist of a particular item or a relation between items. We can now ask a query of Prolog by asking ?.T
14
. sunny is true because (from above) Prolog matches it in its database of facts.
Facts with arguments:
S.2 AIM: Introduction to Facts & Rules. To this query. The facts themselves can consist of any letter or number combination.*.I.sunny. However. or other mathematical operators should be avoided.Mrinalini Rana
CSE7th sem
685034228
3. names containing the characters -.is the Prolog prompt. Facts should always begin with a lowercase letter and end with a full stop. Simple facts:
In Prolog we can make some statements by using facts. ?.E. as well as the underscore _ character. Facts have some simple rules of syntax.+.B.B. For example we can represent the fact that it is sunny by writing the program : sunny.S. Prolog will answer yes./.

let us define the fact that Socrate is a human. A predicate with 2 arguments will be called by predicate_name/2. Facts can have arbitrary number of arguments from zero upwards.mary).. In the above fact john and mary are two atomes.T
15
. The basic Prolog terms are an integer. 'two words' 'UpperCase' '12444' 'etc.Mrinalini Rana
CSE7th sem
685034228
More complicated facts consist of a relation and the items that this refers to.<argument2>.mary). a variable or a structure.I. These items are called arguments.human(X).. The number of arguments is the arity of the predicate.
S. To continue with this example. Atoms are usally made from letters and digits with lowercase characters. It can be read as either john likes mary or mary likes john. Our program will be : mortal(X) :. such as floating point numbers. say that there is a relation between john and mary.E.B. an atom. or strings. The arguments can be any legal Prolog term. The underscore (_) can also be used to separe 2 words but is not allowed as the first charactere. Exemple : likes(john..S.B.human(X). however it can also be a source of mistakes. Various Prolog implementation enhance this basic list with other data types. You have to be clear on how you intend to interpret the relation. This reversibility can be very useful to the programmer.
Rules:
Consider the following sentence : 'All men are mortal' We can express this thing in Prolog by : mortal(X) :. You can have differents predicats with the same name if they have a different arity. The clause can be read as 'X is mortal if X is human'.... The followings are legal atoms :atoms hello zz42 two_words ====> The followings are not legal atoms : Hello 4hello _Hello two words two-words You can use single quotes to make any character combination a legal atom.<argumentN> ).' The fact likes(john. A general model is shown below: relation(<argument1>. Atoms can also be legally made from symbols..

amiga(X). Identical variables names in differents rules are considerated as differents variables and are totally independent. Then Prolog should respond : P=socrate This means that Prolog was able to succed the goal by unifying the variable X to socrates.' to see the following results we was in fact asking 'or'. Like for pure facts. We can do this by using differents rules ands facts with the same name.What) and pressing the key '.'. Again this was done by using the subgoal human(X). The following program : fun(X) :pc(X). If there is no more clauses then it fails and Prolog responds ' no '. If needed the 'or' can also be represebted by '. So from the goal mortal(socrate) Prolog generate the subgoal human(socrate).mortal(X).B. fun(X) :old(X).T 16
.' and the 'or' by differents clause. We can still use variables. In the previous examples when we was asking eats(fred. /* it is old and */ amiga(X). For exeample. We can also see in this example that the 'and' is represented by a '. we can represent the sentence 'Something is fun if it is a PC running UNIX or am old amiga or an ice cream' with the following program : fun(X) :/* something is fun if */ pc(X).Mrinalini Rana
CSE7th sem
685034228
human(socrate). It says that in order to prove that someone is mortal we can prove that he is human. Sometimes we may wish to specify alternatives ways to provre something.mortal(socrate). Prolog will start from the first clause (a clause can be a rule or a fact) of fun and try it.B.S. If that does not succed Prolog will try the next clause. /* it is a pc and */ unix(X). Now if we ask to prolog : ?. Prolog will respond : yes In order to solve the query -? mortal(socrates). /* it is an amiga */ fun(ice_cream).I. unix(X). this is the same as if we had used differents names. /* it is running unix */ fun(X) :/* or it is fun if */ old(X). Prolog will use the rule we have given. /* the ice_crean is also fun */ This program says that there are three ways to know if an object is fun or not. All identically-named variables in a rule (for example X in the last rule we've seem) are of course considered as one unic variable and must have the same instantiation for each solution in a particular query.E. For example we might want to know who is mortal : ?. S.

sunny.T
17
. ?. yes. Add the rule c in the database.assertz()
Example
?. fun(X_2) :old(X_2).Mrinalini Rana Will be seen by Prolog as : fun(X_1) :pc(X_1). An exemple programm can be : eats(fred.asserta() assertz(c). ?.
no.
CSE7th sem
685034228
How to add a rule with a program?
It is possible to add new rules or facts with the instruction Assert (fact1) which will add the fact called fact1. The predicates added with this command are considereted like any other in the source of the program. Remove the c from the database. no.assert(sunny). yes ?.retract(sunny). Add c at the end of the database. amiga(X_2). /* 'Fred eats oranges' */
S.oranges). yes.retract(c) asserta(c).sunny.B.sunny.
How to query:
Once you have entered the facts in a program you can ask prolog about it.I.
The instructions
The usefull instructions are : assert(c). Add c at the beginning of the database.S. ?.B.assert() retract(c). unix(X_1).E.

List). ?List2.eats(john. e. e]. [c. Result). e.oranges).append(FirstBit. S. Append:
The built-in predicate append(?List1. Examples: ?. no /* there is no relation between mike and apple */
3. c. Result = [a. A fairly broad concept of atom is used: this predicate will glue together (or split up) any reasonable characters you give it. that matchs the first clause */ ?. b].that is.I.
This file is a list of the predicates that are built in to our prolog. b. b].apple). to make a word .atom_chars(pizza. or vice-versa.B. e].apple). true. ?. d. c. i. b.S. [b. Atom_chars
The built-in Prolog predicate atom_chars can convert an atom into the list of its constituent letters.E. FirstBit = [a. yes ?. SecondBit. /* does this match anything in the database? */ yes /* yes.append([a. c. e]. e]). A possible list would be to put together a list of letters read.apple). d.3 AIM: Introduction to some Built-in Predicates. b] true.eats(mike.apple). d. ?. r]).B.Mrinalini Rana eats(tony.
1. d. ?List1_then_List2) succeeds if List1 followed by List2 = List1_then_List2. z. b. [a.T 18
. Examples: ?. e] true. /* 'John eats apple' */ If we now ask some queries we would get the followings things : ?. a] ?. [c.
2.atom_chars(Atom. e]). List = [p.
CSE7th sem /* 'Tony eats apple' */
685034228
eats(john. [a.append([a. SecondBit = [c. d. d. one character at a time. z. an atom whose name is the word.eats(fred.

'0'. X=a. ' '.B.atom_codes(Atom. atom_codes :
The built-in Prolog predicate atom_codes can convert an atom into the list of the numeric codes used internally to represent the characters in the atom.atom_codes(pizza. b. '7']
CSE7th sem
685034228
?. X=a. Examples: ?.Mrinalini Rana Atom = beer ?. a.atom_chars(2007. List).4]'
3. fail.member(X.
S.atom_chars(Atom. check if X is in the Rest You may not think of member as a backtracking predicate. % otherwise. '4'.I.T
19
.B. ['['. % X is a member if it’s the first element member(X. but backtracking is built into Prolog. 101. fail. Atom = '[3 . 114]). or vice-versa. a]). 122.'. so in suitable circumstances. [a. Member:
Here is the definition of the built-in Prolog predicate member: member(X. [a. X=a. '0'. [X | Rest]). X=b. '. fail.member(a. Rest).member(X.S. ']']). [a. true . [98. a. 122. true . X=c. 101. What about ?. 97] ?. [Y | Rest]) :member(X. List). true . '3'. Atom = beer
4. 105. Here member backtracks to find every possible solution to the query given to it. Here member backtracks even though it keeps on finding the same answer.E. a]). member will backtrack: ?. List = ['2'. X=a. Consider also: ?. List = [112. c]).

I. Person = _G180 List = [mary.
6. Functor.functor(likes. likes(Person.functor(likes(X.B. pizza). if Goal has no solutions. Arity). Functor = likes Arity = 2 ?. (In other cases. which succeeds if Term is a term with functor Functor and arity Arity. which. pizza). as the name suggests.B. There is also a built-in predicate functor with three arguments: functor(Term. you would want the goal to fail if there are no solutions. always fails. pizza) :. john). feb. -List) is used to collect a list List of all the items Template that satisfy some goal Goal.There is also a built-in predicate called functor. Arity). Useful for forcing backtracking and in various other contexts. 1963)) the top-level functor is termed the principal functor .in this case persondata . This can be convenient if you don't want your goal to fail just because the collection of solutions is empty. likes(marco.S. In a more complex structure.italian(Human). likes is the functor. Arity). marco. Fail:
Built-in Prolog predicate with no arguments. Example: assume likes(mary. Findall:
The built-in predicate findall(+Template.)
7. pizza).functor(likes(mary. Bag).T 20
. Examples: ?.Mrinalini Rana
CSE7th sem
685034228
5. likes(Human. italian(marco). the word functor is used to refer to the atom at the start of a structure. Functor. Then ?. pizza). used to extract the functor and arity of a structure.findall(Person. date(28. X = _G180 Y = _G181 Functor = likes Arity = 2 ?. in likes (mary. For example. marco] findall succeeds and binds List to the empty list. S. +Goal. like persondata(name(smith.E. Functor. Functor. pizza). Y). Arity). Functor:
In Prolog.

?. B.A < B -> Min = A . 2. Lists:
A list in Prolog is written as a comma-separated sequence of items.functor(X. Example: ?. assumes that A and B are numbers) says "if A < B then unify Min with A otherwise unify Min with B".
10. B. … functions as an if … then … else … facility. Prolog arranges for the second argument.S. flush_output.B < A. 3] is a list.X is 2 + 4. X = likes(_G232. 2). between square brackets. [1. get_byte(C).A <= B. one writes the list as [First | Rest].B. Min = B.T
21
. if-then-else. the arithmetic expression 2 + 4. is:
The “is” built-in predicate is used in Prolog to force the evaluation of arithmetic expressions. and unifies it with the variable X.
S. B) :. A list with just a single item. A) :. Read:
read(X) which reads the next term in the current input stream. is written [7]. Example: min(A. ->:
The built-in infix predicate … -> …. This version of min (which. X = 2+4 If instead you write X is 2 + 4. not to 6.X = 2 + 4. min(A. the result is to bind X to the unevaluated term 2 + 4.Mrinalini Rana Functor = likes Arity = 0 ?. say the number 7. B.B.E. read_a_char(C):Write ('Type: '). X=6
11. like the one below.
9.I. Min) :. For example. Possibly it is easier to understand a two-rule version of min: min(A. The empty list is written []. If you just write something like X = 2 + 4. and a list consisting of the rest of the items. In this case. Frequently it is convenient to refer to a list by giving the first item. _G233)
CSE7th sem
685034228
8. which means the window on your workstation unless you have done something slightly fancy with files. likes. to be evaluated (giving the result 6) before binding the result to X.

e. 3]
12. 2.(3. in likes(mary. Name). precedence in Prolog :
Syntax: : . +Type. as X + 1.I. but 23 does not .that is.one that makes sense as a goal . we could write [1.B. where Rest is bound to [2. the second version is much easier to read. Prolog terms normal begin with the functor (e. For example.P. and prefix operators in Prolog terms. 3] [First | [2. It is defined as: once(P) :. 2.
13. 3].style syntax. So for example.op (+Precedence.and calls the term in such a way as to produces just one solution. This can be done as follows: : . 3] [1.for example.e. where First is bound to 1. You may wish to add infix operators of your own. as a prefix operator: not P. 3 | []]
and many more possibilities. prefix. rather than +(X.B. X = [1. and 3] as: • • • • • • [1 | [2. and in practice people use the [1.S. happy(X) makes sense as a goal. infix. xfy.op (700.Mrinalini Rana
CSE7th sem
685034228
We have expressed this here using variable. In this case. 2 | [3]] [1. However. for example.E. . and). and Rest is bound to [2. and postfix operators. Example: ?. you might wish to define an infix and. the empty list atom ([]) must be used to terminate the list. a full stop or period.g. pizza)) but exceptions exist . The table below lists the predefined infix operators in SWI-Prolog.(2. . arithmetic expressions are written in the usual infix way (i. but this need not be so. The Prolog built-in predicate op serves to define the Type and Precedence of infix and postfix. using the built-in predicate name . 1)). 3]] [1 | Rest]. and negation can be written without parentheses.g. 2.(1. which must be a "callable term" .
S. You should always write your Prolog list in the most compact reasonable format. 3]]. !. so you should use it. this approach is more cumbersome. while [X | []] is the same list as [X]. . where First is bound to 1 [First | Rest]. []))). 2. likes.X = .T
22
. op. Lists can also be expressed using a normal term syntax. Once:
The built-in Prolog extra-logical predicate once takes a single argument.

likes(mary.B.likes(mary. fail. pizza).S. If you want to remove.
16. but needs to get rid of them at the start of the next query. Retractall:
What a call to retract actually does is to remove the first fact or rule that matches the argument to retract. This initiates a new call to repeat.B. all the facts relating to likes with two arguments.rich(X). ?. it looks as though you might have to call retract repeatedly. Don't worry about the X = _G180. ?. Repeat:
The built-in predicate repeat behaves as if defined by: repeat. famous(X))). Never fear. ?. pizza).E. retract can be used to clean the discovered facts out of the database. ?.assert(likes(mary.I. and concludes that the fact or rule was wrong. If the Prolog interpreter subsequently backtracks. discovers some new facts in each run. true. So then the program retracts the fact or rule.repeat. you might simply have a query that runs repeatedly during a single prolog session. thanks to the first clause. ?. famous(X))). For example. your program might have hypothesised that some fact or rule is correct. as opposed to the fact.retract(likes(mary. and so on.
S. So again. say.T
23
. true. pizza)). X = _G180 true.
15. which succeeds via the first clause.rich(X). the second clause (repeat :. ?. Retract:
Retract is a built-in meta-predicate used to remove facts or rules from the Prolog database while a program is executing.assert((happy(X) :. X = _G180 true. repeat :. More prosaically.repeat. then your program explores the consequences of that assumption. pizza)).retract((happy(X) :. added it to the Prolog database using assert (or one of its relatives). true. Note also the extra pair of parentheses () around the rule. that's just SWI Prolog renaming the variable X with a unique name so it doesn't get confused with the (different) variable X that you might have used in some other rule. It is most often used in partnership with assert (or one of its relatives).Mrinalini Rana
CSE7th sem
685034228
14. Thus repeat succeeds when first called.) is tried.

– unary minus Try the query X is 1. pizza)). pizza). assert(likes(john. likes(mary. always succeeds
19.Mrinalini Rana
CSE7th sem
685034228
retractall is here! This meta-predicate. fail. True:
Built-in Prolog predicate with no arguments. This is to stop the program modifying unauthorised parts of itself. Setof:
The built-in Prolog predicate setof(+Template. happy(harry). happy(Y). beer).
18. X = _G180 Y = _G181 ?. For example: ?.
S. and becoming totally un-debuggable. Y)).E.B. – subtraction 1 is 2 – 1.rich(X). happy(X) :. beer)).X.B. -Set) binds Set to the list of all instances of Template satisfying the goal Goal. Arithmetic:
Many of the usual arithmetic operators are available in Prolog: Operator Meaning Example + addition 2 is 1 + 1. true. as its name suggests. given the facts and rule: happy(fido). Example continues: ?. rich(harry).S. +Goal. :.T
24
.I. :. true.listing(likes). The ":. likes(john.dynamic likes/2.assert(likes(mary. ?. harry] .dynamic/2" tells us that likes/2 is a built-in predicate that can be modified during program execution (see dynamic). Y is .dynamic likes/2.
17.listing(likes). Y = _G180 Set = [fido. which. For example. Set). it follows that ?.setof(Y. as the name suggests. retracts all facts or rules that match its single argument.retractall(likes(X.

. If you wanted to be more cautious. ?.1 is Num mod 2. pizza) What = pizza
S.210000000001. [likes. actually fails when typed into Prolog as a query. odd(Num) :. as represented in computers.E. Call:
Call is a built-in meta-predicate that allows its single argument to be called/invoked as a goal. Here are queries that perform these roles .call(likes(Person.B. both the assert and the call would be built in to Prolog procedures written by the programmer.in a real program.21 is 1. 1. or perhaps a arithmetic comparison goal like this: 2. integer division 1 is 7 // 4. with fractional numbers.1 ** 2.T
25
.Num mod 2 =:= 1. need to test the goal. exponentiation 1. presumably later in the program.
20. mary. For example.
Except in the context of an arithmetic comparison operator. a program might create a goal (perhaps using =.B. X = Y + 2 where Y is a variable already bound to a numeric value. division 2 is 6 / 3.Goal =. pizza)). As usual in digital computations. odd(Num) :. ?.Mrinalini Rana * / // mod **
CSE7th sem
685034228
multiplication 4 is 2 * 2. actually comes out to be something like 1. 1 is Num mod 2.. See the section on comparison operators for a solution to this issue. Thus the final example in the table above. X > Y * Z Here's another example: a rule to tell if a (whole) number is odd: 3. Goal = likes(mary. using the is built-in predicate. you could first check that Num is in fact a whole number: 5. call(Goal).1 ** 2. Another way to do this one is to use =:=: 4.1 ** 2. Person = mary ?. Mostly one uses these operators in a goal more like this: 1. and then.integer(Num). This is because 1.21 is 1.I.S. integer remainder 3 is 7 mod 4. odd(Num) :. arithmetic expressions need to be explicitly evaluated in Prolog. it is necessary to be careful with approximation issues. pizza)). What].) on the fly.assert(likes(mary.

E. ?-likes(john.S.flowers).4 AIM: Introduction to PROLOG programming by PROLOG programs.B. likes(mary.mary).
1.Mrinalini Rana
CSE7th sem
685034228
3.flowers).mary).
Output:
S.
Program:
likes(john.T
26
. Write a simple program in PROLOG.I.B. likes(john.

likes(mary.Mrinalini Rana
CSE7th sem
685034228
2.
Output:
S.T
27
.B.E. likes(john.S.
Program:
likes(john.mary).write(X).B. ?-likes(john.I. Write a program to print the value of variable.X).flowers).flowers).

a.pin.ToPin.ToPin])._).ToPin).ToPin.UsingPin):-M is N-1.b.c). move(From.from.
Program:
hanoi(N):-hanoi(N.
Output:
S.E.S._.pin.FromPin.FromPin.UsingPin).to.T 28
.UsingPin).B.UsingPin. hanoi(M.FromPin).from.FromPin.I. hanoi(N. move(FromPin.N>1. Write a program of Tower of Hanoi.fromPin.ToPin.To):-write([move.B. hanoi(M._. ?-hanoi(N.disk.Mrinalini Rana
CSE7th sem
685034228
3. hanoi(N.

I.write(X).1).T
29
.E.Z).B.
Program:
factorial(0.S. factorial(X.factorial(15. Write a program of factorial.Mrinalini Rana
CSE7th sem
685034228
4.Y) :X1 is X .
Output:
S.X).!. ?.B. Y is Z*X. factorial(X1.1.

[1.T
30
.member(2.R). member(X.S.3]).B.
Output:
S. Write a program to find member from a list.
Program:
member(X.I. ?.B.2.[Y|R]) :.[X|R]).member(X.E.Mrinalini Rana
CSE7th sem
685034228
5.

fib(N.fib(7.
Program:
fib(1.R is R1+R2.E.S.N2 is N-2. fib(N1.Mrinalini Rana
CSE7th sem
685034228
6. Write a program to find the fibonnacci series.R1).R):.I.R2).N1 is N-1.
Output:
S.fib(N2.N >= 3.write(R). fib(2. ?.T 31
.1).B.R).1).B.

S. N1 is N-1.N\=1. Write a prolog program to print the sum of n numbers. R is N+R1.
PROGRAM:
sum_to(1.B.Mrinalini Rana
CSE7th sem
685034228
7.I.1).write(X).X). sum_to(N1.E.R1). ?-sum_to(6.T
32
.
S. sum_to(N.B.R):.

S. ?-aless (advocate.E.
Program:
aless(advocate.Mrinalini Rana
CSE7th sem
685034228
Output:
8.clergyman).I.T
33
. Write a program using aless predicate.
Output:
S.B.clergyman).B.

boy(paul).E.S.B. girl(ritika). Write a program to get the possible pairs.B. boy(krishana).I.T 34
. girl(ridhima). S.Mrinalini Rana
CSE7th sem
685034228
9.
Program:
boy(rohan). girl(komal).

S.I.Mrinalini Rana possible_pair(X.
Output:
10.Y):-boy(X). alter([]. change(X.E.[]).i).no).T 35
.write(X).B. change(are. S.X).not]). Write a program to use change predicate.[am.
Program:
change(you. change(do.german). change(frence.Y).girl(Y).
CSE7th sem
685034228
?-possible_pair(X.B.write(Y).

a.S.alter(T.E.B.Y).computer].B.are.Z).I.X). ?-alter([you.[X|Y]):-change(H.write(Z).Mrinalini Rana
CSE7th sem
685034228
alter([H|T].T
36
.
Output:
S.