96 vues

Titre original : Pro Log File

Transféré par Gursimran Bedi

- Arabic Transcription
- Mini Project
- Matching SHIQ Ontologies
- confdltBojanczyk09
- class notes on IOS.docx
- Menzel TheTrueModalLogic
- formal method
- edge on
- Introduction to Prolog
- The Bell and LaPadula Security model.pdf
- logic of exception
- Klimovsky Axiomatica resumen.pdf
- Prolog-2
- Disputatio Vol. IV No. 34 Logic Norms and Ontology2
- Discrete Math and Functional Programming
- WHAT IS TEMPORAL ONTOLOGY.pdf
- The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
- Sapiens: A Brief History of Humankind
- The Unwinding: An Inner History of the New America
- Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race

Vous êtes sur la page 1sur 36

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

(Affiliated to PTU)

Lect.Gurpreet Singh Mrinalini Rana

685034228

CSE (7th sem)

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

Mrinalini Rana CSE7th sem 685034228

PRACTICAL NO.1:

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:

• 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:

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 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”.

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.

recursively as follows:

2. If α is a well-formed formula, then so is ¬α .

3. If α and β are well-formed formulas, then so is (α & β) .

4. If α and β are well-formed formulas, then so is (α v β) .

5. If α and β are well-formed formulas, then so is (α → β) .

6. If α and β are well-formed formulas, then so is (α ↔ β) .

7. Nothing that cannot be constructed by successive steps of (1)-(6) is a well-formed

formula.

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

Mrinalini Rana CSE7th sem 685034228

So far we have in effect described the grammar of language PL. When setting up a

language fully, however, it is necessary not only to establish rules of grammar, but also

describe the meanings of the symbols used in the language. We have already suggested

that uppercase letters are used as complete simple statements. Because truth-functional

propositional logic does not analyze the parts of simple statements, 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, in effect, it

does not matter what meaning we assign to the individual statement letters like ‘P’, ‘Q’

and ‘R’, etc., provided that each is taken as either true or false (and not both).

true if both α and β are true, and is false if either α is false or β is false or both are false. In

effect, the meaning of the operator ‘&’ can be displayed according to the following chart,

which shows the truth-value of the conjunction depending on the four possibilities of the

truth-values of the parts:

α β (α & β)

T T T

T F F

F T F

F F F

if either α is true or β is true, or both α and β are true, and is false only if both α and β are

false. A chart similar to that given above for conjunction, modified for to show the

meaning of the disjunction sign ‘v‘ instead, would be drawn as follows:

α β (α v β)

T T T

T F T

F T T

F F F

Material Implication: This truth-function is represented in language PL with the sign ‘→’.

A statement of the form (α → β) , is false if α is true and β is false, and is true if either α

is false or β is true (or both). This truth-function generates the following chart:

α β (α → β)

T T T

T F F

F T T

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

Mrinalini Rana CSE7th sem 685034228

F F T

‘↔’. A statement of the form (α ↔ β) is regarded as true if α and β are either both true

or both false, and is regarded as false if they have different truth-values. Hence, we have

the following chart:

α β (α ↔ β)

T T T

T F F

F T F

F F T

true if α is false, and false if α is true. Unlike the other operators we have considered,

negation is applied to a single statement. The corresponding chart can therefore be drawn

more simply as follows:

α ¬α

T F

F T

c. Rules of Inference

Here we give a list of intuitively valid rules of inference. The rules are stated in schematic

form. 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.

α→β

α

β

form of “→-elimination”.)

α→β

¬β

¬α

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

Mrinalini Rana CSE7th sem 685034228

(Modus tollens is sometimes also called “modus tollendo tollens” or a form of “→-

elimination”.)

d. Semantics

constants in that language. It also determines a domain of discourse that specifies the

range of the quantifiers. The result is that each term is assigned an object that it

represents, and each sentence is assigned a truth value. In this way, an interpretation

provides semantic meaning to the terms and formulas of the language. The study of the

interpretations of formal languages is called formal semantics.

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

Mrinalini Rana CSE7th sem 685034228

PRACTICAL NO.2:

First-order logic is a formal logic used in mathematics, philosophy, linguistics, and

computer science. It goes by many names, including: first-order predicate calculus, the

lower predicate calculus, and predicate logic. First-order logic is distinguished from

propositional logic by its use of quantifiers; each interpretation of first-order logic

includes a domain of discourse over which the quantifiers range.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). Although the logical

consequence relation is only semidecidable, much progress has been made in automated

theorem proving in first-order logic.

set of axioms is often finite or recursively enumerable, in which case the theory is called

effective. Some authors require theories to also include all logical consequences of the

axioms.

A first-order structure that satisfies all sentences in a given theory is said to be a model of

the theory. An elementary class is the set of all structures satisfying a particular theory.

These classes are a main subject of study in model theory.

propositional logic) and also about quantification ("all" or "some"). A classic, if

elementary, example of what can be done with the predicate logic is the inference from

the premises:

• Socrates is a man. to the conclusion

Quantifiers:

P holds for all values of x in the domain associated with that variable.

–E.g., (Ax) dolphin(x) => mammal(x)

•

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

Mrinalini Rana CSE7th sem 685034228

holds for some value of x in the domain associated with that variable.

–E.g., (Ex) mammal(x) ^ lays-eggs(x)

•

•Universal quantifiers are usually used with "implies" to form "if-then rules."

–E.g., (Ax) cs15-381-student(x) => smart(x) means "All cs15-381 students are smart."

–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.

•Existential quantifiers are usually used with "and" to specify a list of properties or facts

about an individual.

–E.g., (Ex) cs15-381-student(x) ^ smart(x) means "there is a cs15-381 student who is

smart."

–A common mistake is to represent this English sentence as the FOL sentence: (Ex) cs15-

381-student(x) => smart(x)

•

•Switching the order of universal quantifiers does not change the meaning: (Ax)

(Ay)P(x,y) is logically equivalent to (Ay)(Ax)P(x,y). Similarly, you can switch the order

of existential quantifiers.

•

•Switching the order of universals and existentials does change meaning:

–Everyone likes someone: (Ax)(Ey)likes(x,y)

–Someone is liked by everyone: (Ey)(Ax)likes(x,y)

–A term (denoting a real-world object) is a constant symbol, a variable symbol, or a

function e.g. left-leg-of ( ). For example, x and f(x1, ..., xn) are terms, where each xi is a

term.

–An atom (which has value true or false) is either an n-place predicate of n terms, or, if P

and Q are atoms, then ~P, P V Q, P ^ Q, P => Q, P <=> Q are atoms

–A sentence is an atom, or, if P is a sentence and x is a variable, then (Ax)P and (Ex)P

are sentences

–A well-formed formula (wff) is a sentence containing no "free" variables. I.e., all

variables are "bound" by universal or existential quantifiers.

•E.g., (Ax)P(x,y) has x bound as a universally quantified variable, but y is free.

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

Mrinalini Rana CSE7th sem 685034228

•

•You can fool some of the people all of the time. (Ex)(At) (person(x) ^ time(t)) => can-

fool(x,t)

•

•You can fool all of the people some of the time. (Ax)(Et) (person(x) ^ time(t) => can-

fool(x,t)

•

•All purple mushrooms are poisonous. (Ax) (mushroom(x) ^ purple(x)) =>

poisonous(x)

•No purple mushroom is poisonous. ~(Ex) purple(x) ^ mushroom(x) ^ poisonous(x)

or, equivalently, (Ax) (mushroom(x) ^ purple(x)) => ~poisonous(x)

•

•There are exactly two purple mushrooms. (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. ~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. (Ax)(Ay)

above(x,y) <=> (on(x,y) v (Ez) (on(x,z) ^ above(z,y)))

•Inference rules for PL apply to FOL as well. For example, Modus Ponens, And-

Introduction, And-Elimination, etc.

•New sound inference rules for use with quantifiers:

–UniversalElimination

If (Ax)P(x) is true, then P(c) is true, where c is a constant in the domain of x. For

example, from (Ax)eats(Ziggy, x) we can infer eats(Ziggy, IceCream).

•The variable symbol can be replaced by any ground term, i.e., any constant symbol or

function symbol applied to ground terms only.

–ExistentialIntroduction

If P(c) is true, then (Ex)P(x) is inferred.

•For example, from eats(Ziggy, IceCream) we can infer (Ex)eats(Ziggy, x).

•All instances of the given constant symbol are replaced by the new variable symbol.

Note that the variable symbol cannot already exist anywhere in the expression.

–ExistentialElimination

From (Ex)P(x) infer P(c).

•For example, from (Ex)eats(Ziggy, x) infer eats(Ziggy, Cheese).

•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. In other words, we don't want to accidentally

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

Mrinalini Rana CSE7th sem 685034228

draw other inferences about it by introducing the constant. All we know is there must be

some constant that makes this true, so we can introduce a brand new one to stand in for

that (unknown) constant.

Semantics:

An interpretation of a first-order language assigns a denotation to all non-logical

constants in that language. It also determines a domain of discourse that specifies the

range of the quantifiers. The result is that each term is assigned an object that it

represents, and each sentence is assigned a truth value. In this way, an interpretation

provides semantic meaning to the terms and formulas of the language. The study of the

interpretations of formal languages is called formal semantics.

first-order formula is a statement about these objects; for example, states the

existence of an object x such that the predicate P is true where referred to it. The domain

of discourse is the set of considered objects. For example, one can take D to be the set of

integer numbers.

A formula evaluates to true or false given an interpretation, and a variable assignment μ

that associates an element of the domain of discourse with each variable. The reason that

a variable assignment is required is to give meanings to formulas with free variables, such

as y = x. The truth value of this formula changes depending on whether x and y denote

the same individual.

First, the variable assignment μ can be extended to all terms of the language, with the

result that each term maps to a single element of the domain of discourse. The following

rules are used to make this assignment:

2. Functions. Given terms that have been evaluated to elements

of the domain of discourse, and a n-ary function symbol f, the term

evaluates to .

Next, each formula is assigned a truth value. The inductive definition used to make this

assignment is called the T-schema.

false depending on whether , where are the

evaluation of the terms and I(P) is the interpretation of P, which by

assumption is a subset of Dn.

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

Mrinalini Rana CSE7th sem 685034228

same object of the domain of discourse (see the section on equality below).

3. Logical connectives. A formula in the form , , etc. is evaluated

according to the truth table for the connective in question, as in propositional

logic.

4. 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 μ'. 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.

5. Universal quantifiers. 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. This captures the idea that

is true if every possible choice of a value for x causes φ(x) to be true.

If a formula does not contain free variables, and so is a sentence, then the initial variable

assignment does not affect its truth value. In other words, a sentence is true according to

M and μ if and only if is true according to M and any other variable assignment μ'.

There is a second common approach to defining truth values that does not rely on variable

assignment functions. Instead, given an interpretation M, one first adds to the signature a

collection of constant symbols, one for each element of the domain of discourse in M; say

that for each d in the domain the constant symbol cd is fixed. The interpretation is

extended so that each new constant symbol is assigned to its corresponding element of the

domain. One now defines truth for quantified formulas syntactically, as follows:

there is some d in the domain of discourse such that φ(cd) holds. Here φ(cd) is the

result of substituting cd for every free occurrence of x in φ.

2. Universal quantifiers (alternate). A formula is true according to M if,

for every d in the domain of discourse, φ(cd) is true according to M.

This alternate approach gives exactly the same truth values to all sentences as the

approach via variable assignments.

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

Mrinalini Rana CSE7th sem 685034228

PRACTICAL NO.3:

Prolog is a logic programming general purpose fifth generation language associated with

artificial intelligence and computational linguistics. It has a purely logical subset, called

"pure Prolog", as well as a number of extralogical features.

Prolog has its roots in formal logic, and unlike many other programming languages,

Prolog is declarative: The program logic is expressed in terms of relations, and execution

is triggered by running queries over these relations. Relations and queries are constructed

using Prolog's single data type, the term. Relations are defined by clauses. Given a query,

the Prolog engine attempts to find a resolution refutation of the negated query. If the

negated query can be refuted, i.e., an instantiation for all free variables is found that

makes the union of clauses and the singleton set consisting of the negated query false, it

follows that the original query, with the found instantiation applied, is a logical

consequence of the program. This makes Prolog (and other logic programming

languages) particularly useful for database, symbolic mathematics, and language parsing

applications. Because Prolog allows impure predicates, checking the truth value of certain

special predicates may have some deliberate side effect, such as printing a value to the

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

Mrinalini Rana CSE7th sem 685034228

screen. This permits the programmer to use some amount of conventional imperative

programming when the logical paradigm is inconvenient.

Programming in Prolog is very different from programming in a traditional

proceduralprocedural language like Pascal. In Prolog you don't say how the program will

work.

Prolog can be separated in two parts:

The Program

The program, sometimes called Database is a texte file (*.pl) that contain the facts and

rules that will be used by the user of the program. It contains all the relations that make

this program.

The Query

When you launch a program you are in query modequery mode. This mode is represented

by the sign? - At the begining of the line. In query mode you ask questions about relations

described in the program.

Loading a program:

Loading First you have to launch your Prolog compiler, for this report we used the SWI-

Prolog wich is a freeware (if you want to know more about SWI-Prolog go to this page).

When Prolog is launched the? - should appear meaning you are in query mode. The

manier to launch a program depends of your compiler. For SWI-Prolog you can load a

program by typing the cammand [file]. When the file of your program is file.pl. If you

compiler is not SWI-Prolog you can also try the command reconsult(file). When you have

done this you can use all the facts and rules that are contained in the program. Now let's

begin to see what a fact...is

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

Mrinalini Rana CSE7th sem 685034228

Simple facts:

In Prolog we can make some statements by using facts. Facts either consist of a particular

item or a relation between items. For example we can represent the fact that it is sunny by

writing the program :

sunny.

We can now ask a query of Prolog by asking

?- sunny.

?- is the Prolog prompt. To this query, Prolog will answer yes. sunny is true because

(from above) Prolog matches it in its database of facts.

Facts have some simple rules of syntax. Facts should always begin with a lowercase letter

and end with a full stop. The facts themselves can consist of any letter or number

combination, as well as the underscore _ character. However, names containing the

characters -,+,*,/, or other mathematical operators should be avoided.

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

Mrinalini Rana CSE7th sem 685034228

More complicated facts consist of a relation and the items that this refers to. These items

are called arguments. Facts can have arbitrary number of arguments from zero upwards.

A general model is shown below:

relation(<argument1>,<argument2>,....,<argumentN> ).

The arguments can be any legal Prolog term. The basic Prolog terms are an integer, an

atom, a variable or a structure. Various Prolog implementation enhance this basic list with

other data types, such as floating point numbers, or strings.

Exemple :

likes(john,mary).

In the above fact john and mary are two atomes. Atoms are usally made from letters and

digits with lowercase characters. The underscore (_) can also be used to separe 2 words

but is not allowed as the first charactere. Atoms can also be legally made from symbols.

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.

'two words'

'UpperCase'

'12444'

'etc...'

The fact likes(john,mary). say that there is a relation between john and mary. It can be

read as either john likes mary or mary likes john. This reversibility can be very useful to

the programmer, however it can also be a source of mistakes. You have to be clear on

how you intend to interpret the relation. The number of arguments is the arity of the

predicate. A predicate with 2 arguments will be called by predicate_name/2. You can

have differents predicats with the same name if they have a different arity.

Rules:

Consider the following sentence : 'All men are mortal' We can express this thing in Prolog

by :

mortal(X) :- human(X).

The clause can be read as 'X is mortal if X is human'.

To continue with this example, let us define the fact that Socrate is a human. Our program

will be :

mortal(X) :- human(X).

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

Mrinalini Rana CSE7th sem 685034228

human(socrate).

Now if we ask to prolog :

?- mortal(socrate).

Prolog will respond :

yes

In order to solve the query -? mortal(socrates). Prolog will use the rule we have given. It

says that in order to prove that someone is mortal we can prove that he is human. So from

the goal mortal(socrate) Prolog generate the subgoal human(socrate).

We can still use variables. For example we might want to know who is mortal :

?- mortal(X).

Then Prolog should respond :

P=socrate

This means that Prolog was able to succed the goal by unifying the variable X to socrates.

Again this was done by using the subgoal human(X).

Sometimes we may wish to specify alternatives ways to provre something. We can do this

by using differents rules ands facts with the same name. For exeample, 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), /* it is a pc and */

unix(X). /* it is running unix */

fun(X) :- /* or it is fun if */

old(X), /* it is old and */

amiga(X). /* it is an amiga */

fun(ice_cream). /* the ice_crean is also fun */

This program says that there are three ways to know if an object is fun or not. Like for

pure facts, Prolog will start from the first clause (a clause can be a rule or a fact) of fun

and try it. If that does not succed Prolog will try the next clause. If there is no more

clauses then it fails and Prolog responds ' no '. We can also see in this example that the

'and' is represented by a ',' and the 'or' by differents clause. If needed the 'or' can also be

represebted by ';'. In the previous examples when we was asking eats(fred,What) and

pressing the key ';' to see the following results we was in fact asking 'or'.

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. Identical variables names in differents rules are

considerated as differents variables and are totally independent, this is the same as if we

had used differents names.

The following program :

fun(X) :-

pc(X),

unix(X).

fun(X) :-

old(X),

amiga(X).

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

Mrinalini Rana CSE7th sem 685034228

fun(X_1) :-

pc(X_1),

unix(X_1).

fun(X_2) :-

old(X_2),

amiga(X_2).

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.

The instructions

assert(c). Add the rule c in the database.assert()

retract(c). Remove the c from the database.retract(c)

asserta(c). Add c at the beginning of the database.asserta()

assertz(c). Add c at the end of the database.assertz()

Example

?- sunny.

no.

?- assert(sunny).

yes.

?- sunny.

yes

?- retract(sunny).

yes.

?- sunny.

no.

How to query:

Once you have entered the facts in a program you can ask prolog about it. An exemple

programm can be :

eats(fred,oranges). /* 'Fred eats oranges' */

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

Mrinalini Rana CSE7th sem 685034228

If we now ask some queries we would get the followings things :

?- eats(fred,oranges).

/* does this match anything in the database? */

yes

/* yes, that matchs the first clause */

?- eats(john,apple).

yes

?- eats(mike,apple).

no

/* there is no relation between mike and apple */

3.3 AIM: Introduction to some Built-in Predicates.

This file is a list of the predicates that are built in to our prolog.

1. Append:

The built-in predicate append(?List1, ?List2, ?List1_then_List2) succeeds if List1

followed by List2 = List1_then_List2. Examples:

Result = [a, b, c, d, e].

true.

?- append([a, b], SecondBit, [a, b, c, d, e]).

SecondBit = [c, d, e]

true.

?- append(FirstBit, [c, d, e], [a, b, c, d, e]).

FirstBit = [a, b]

true.

2. Atom_chars

The built-in Prolog predicate atom_chars can convert an atom into the list of its

constituent letters, or vice-versa. A fairly broad concept of atom is used: this predicate

will glue together (or split up) any reasonable characters you give it. A possible list would

be to put together a list of letters read, one character at a time, to make a word - that is, an

atom whose name is the word. Examples:

?- atom_chars(pizza, List).

List = [p, i, z, z, a]

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

Mrinalini Rana CSE7th sem 685034228

Atom = beer

?- atom_chars(2007, List).

List = ['2', '0', '0', '7']

Atom = '[3 ,4]'

3. 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, or vice-versa. Examples:

?- atom_codes(pizza, List).

List = [112, 105, 122, 122, 97]

Atom = beer

4. Member:

Here is the definition of the built-in Prolog predicate member:

member(X, [X | Rest]). % X is a member if it’s the first element

member(X, [Y | Rest]) :-

member(X, Rest). % otherwise, check if X is in the Rest

You may not think of member as a backtracking predicate, but backtracking is built into

Prolog, so in suitable circumstances, member will backtrack:

X=a;

X=b;

X=c;

fail.

Here member backtracks to find every possible solution to the query given to it. Consider

also:

?- member(X, [a, a, a]).

X=a;

X=a;

X=a;

fail.

Here member backtracks even though it keeps on finding the same answer. What about

?- member(a, [a, a, a]).

true ;

true ;

true ;

fail.

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

Mrinalini Rana CSE7th sem 685034228

5. Fail:

Built-in Prolog predicate with no arguments, which, as the name suggests, always fails.

Useful for forcing backtracking and in various other contexts.

6. Findall:

The built-in predicate findall(+Template, +Goal, -List) is used to collect a list List of all

the items Template that satisfy some goal Goal.

Example: assume

likes(mary, pizza).

likes(marco, pizza).

likes(Human, pizza) :- italian(Human).

italian(marco).

Then

Person = _G180

List = [mary, marco, marco]

findall succeeds and binds List to the empty list, if Goal has no solutions. This can be

convenient if you don't want your goal to fail just because the collection of solutions is

empty. (In other cases, you would want the goal to fail if there are no solutions.)

7. Functor:

In Prolog, the word functor is used to refer to the atom at the start of a structure. For

example, in likes (mary, pizza), likes is the functor. In a more complex structure, like

the top-level functor is termed the principal functor - in this case persondata - There is

also a built-in predicate called functor, used to extract the functor and arity of a structure.

There is also a built-in predicate functor with three arguments: functor(Term, Functor,

Arity), which succeeds if Term is a term with functor Functor and arity Arity. Examples:

Functor = likes

Arity = 2

X = _G180

Y = _G181

Functor = likes

Arity = 2

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

Mrinalini Rana CSE7th sem 685034228

Functor = likes

Arity = 0

X = likes(_G232, _G233)

8. if-then-else, ->:

The built-in infix predicate … -> …; … functions as an if … then … else … facility.

Example:

min(A, B, Min) :- A < B -> Min = A ; Min = B.

This version of min (which, like the one below, assumes that A and B are numbers) says

"if A < B then unify Min with A otherwise unify Min with B". Possibly it is easier to

understand a two-rule version of min:

min(A, B, A) :- A <= B.

min(A, B, B) :- B < A.

9. Read:

read(X) which reads the next term in the current input stream, which means the window

on your workstation unless you have done something slightly fancy with files, and unifies

it with the variable X.

read_a_char(C):-

Write ('Type: '), flush_output,

get_byte(C).

10. is:

The “is” built-in predicate is used in Prolog to force the evaluation of arithmetic

expressions. If you just write something like X = 2 + 4, the result is to bind X to the

unevaluated term 2 + 4, not to 6. Example:

?- X = 2 + 4.

X = 2+4

If instead you write X is 2 + 4, Prolog arranges for the second argument, the arithmetic

expression 2 + 4, to be evaluated (giving the result 6) before binding the result to X.

?- X is 2 + 4.

X=6

11. Lists:

A list in Prolog is written as a comma-separated sequence of items, between square

brackets. For example, [1, 2, 3] is a list.

The empty list is written [].

A list with just a single item, say the number 7, is written [7].

Frequently it is convenient to refer to a list by giving the first item, and a list consisting of

the rest of the items. In this case, one writes the list as [First | Rest].

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

Mrinalini Rana CSE7th sem 685034228

We have expressed this here using variable, but this need not be so, for example, we

could write [1, 2, and 3] as:

• [1 | [2, 3]]

• [1 | Rest], where Rest is bound to [2, 3]

• [First | [2, 3]], where First is bound to 1

• [First | Rest], where First is bound to 1, and Rest is bound to [2, 3]

• [1, 2 | [3]]

• [1, 2, 3 | []]

You should always write your Prolog list in the most compact reasonable format. So for

example, while [X | []] is the same list as [X], the second version is much easier to read,

so you should use it.

Lists can also be expressed using a normal term syntax, using the built-in predicate name

. - that is, a full stop or period. In this case, the empty list atom ([]) must be used to

terminate the list. However, this approach is more cumbersome, and in practice people

use the [1, 2, 3]- style syntax. Example:

X = [1, 2, 3]

12. Once:

The built-in Prolog extra-logical predicate once takes a single argument, which must be a

"callable term" - one that makes sense as a goal - e.g. happy(X) makes sense as a goal, but

23 does not - and calls the term in such a way as to produces just one solution. It is

defined as:

once(P) :- P, !.

Syntax:

: - op (+Precedence, +Type, Name).

The Prolog built-in predicate op serves to define the Type and Precedence of infix and

postfix, and prefix operators in Prolog terms. Prolog terms normal begin with the functor

(e.g. likes, in likes(mary, pizza)) but exceptions exist - for example, arithmetic

expressions are written in the usual infix way (i.e. as X + 1, rather than +(X, 1)), and

negation can be written without parentheses, as a prefix operator: not P.

The table below lists the predefined infix operators in SWI-Prolog. You may wish to add

infix operators of your own. For example, you might wish to define an infix and. This can

be done as follows:

: - op (700, xfy, and).

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

Mrinalini Rana CSE7th sem 685034228

14. Repeat:

The built-in predicate repeat behaves as if defined by:

repeat.

repeat :- repeat.

Thus repeat succeeds when first called, thanks to the first clause. If the Prolog interpreter

subsequently backtracks, the second clause (repeat :- repeat.) is tried. This initiates a new

call to repeat, which succeeds via the first clause, and so on.

15. Retract:

Retract is a built-in meta-predicate used to remove facts or rules from the Prolog database

while a program is executing. It is most often used in partnership with assert (or one of its

relatives). For example, your program might have hypothesised that some fact or rule is

correct, added it to the Prolog database using assert (or one of its relatives), then your

program explores the consequences of that assumption, and concludes that the fact or rule

was wrong. So then the program retracts the fact or rule.

More prosaically, you might simply have a query that runs repeatedly during a single

prolog session, discovers some new facts in each run, but needs to get rid of them at the

start of the next query. So again, retract can be used to clean the discovered facts out of

the database.

?- assert(likes(mary, pizza)).

true.

?- likes(mary, pizza).

true.

?- retract(likes(mary, pizza)).

true.

?- likes(mary, pizza).

fail.

?- assert((happy(X) :- rich(X), famous(X))).

X = _G180

true.

?- retract((happy(X) :- rich(X), famous(X))).

X = _G180

true.

Don't worry about the X = _G180, 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. Note also the extra pair of parentheses () around the rule, as

opposed to the fact.

16. Retractall:

What a call to retract actually does is to remove the first fact or rule that matches the

argument to retract. If you want to remove, say, all the facts relating to likes with two

arguments, it looks as though you might have to call retract repeatedly. Never fear,

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

Mrinalini Rana CSE7th sem 685034228

retractall is here! This meta-predicate, as its name suggests, retracts all facts or rules that

match its single argument. For example:

?- assert(likes(mary, pizza)), assert(likes(john, beer)).

true.

?- listing(likes).

:- dynamic likes/2.

likes(mary, pizza).

likes(john, beer).

The ":- dynamic/2" tells us that likes/2 is a built-in predicate that can be modified during

program execution (see dynamic). This is to stop the program modifying unauthorised

parts of itself, and becoming totally un-debuggable. Example continues:

?- retractall(likes(X, Y)).

X = _G180

Y = _G181

?- listing(likes).

:- dynamic likes/2.

true.

17. Setof:

The built-in Prolog predicate setof(+Template, +Goal, -Set) binds Set to the list of all

instances of Template satisfying the goal Goal.

For example, given the facts and rule:

happy(fido).

happy(harry).

happy(X) :- rich(X).

rich(harry).

it follows that

Y = _G180

Set = [fido, harry] ;

fail.

18. True:

Built-in Prolog predicate with no arguments, which, as the name suggests, always

succeeds

19. Arithmetic:

Many of the usual arithmetic operators are available in Prolog:

+ addition 2 is 1 + 1.

– subtraction 1 is 2 – 1.

– unary minus Try the query X is 1, Y is - X.

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

Mrinalini Rana CSE7th sem 685034228

* multiplication 4 is 2 * 2.

/ division 2 is 6 / 3.

// integer division 1 is 7 // 4.

mod integer remainder 3 is 7 mod 4.

** exponentiation 1.21 is 1.1 ** 2.

to be explicitly evaluated in Prolog, using the is built-in predicate.

Mostly one uses these operators in a goal more like this:

1. X = Y + 2

where Y is a variable already bound to a numeric value, or perhaps a arithmetic

comparison goal like this:

2. X > Y * Z

Here's another example: a rule to tell if a (whole) number is odd:

3. odd(Num) :- 1 is Num mod 2.

Another way to do this one is to use =:=:

4. odd(Num) :- Num mod 2 =:= 1.

If you wanted to be more cautious, you could first check that Num is in fact a whole

number:

5. odd(Num) :- integer(Num), 1 is Num mod 2.

with approximation issues. Thus the final example in the table above, 1.21 is 1.1 ** 2.

actually fails when typed into Prolog as a query. This is because 1.1 ** 2, as represented

in computers, actually comes out to be something like 1.210000000001. See the section

on comparison operators for a solution to this issue.

20. Call:

Call is a built-in meta-predicate that allows its single argument to be called/invoked as a

goal. For example, a program might create a goal (perhaps using =..) on the fly, and then,

presumably later in the program, need to test the goal. Here are queries that perform these

roles - in a real program, both the assert and the call would be built in to Prolog

procedures written by the programmer.

?- assert(likes(mary, pizza)).

?- call(likes(Person, pizza)).

Person = mary

?- Goal =.. [likes, mary, What], call(Goal).

Goal = likes(mary, pizza)

What = pizza

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

Mrinalini Rana CSE7th sem 685034228

programs.

Program:

likes(john,mary).

likes(john,flowers).

likes(mary,flowers).

?-likes(john,mary).

Output:

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

Mrinalini Rana CSE7th sem 685034228

Program:

likes(john,mary).

likes(john,flowers).

likes(mary,flowers).

?-likes(john,X),write(X).

Output:

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

Mrinalini Rana CSE7th sem 685034228

Program:

hanoi(N):-hanoi(N,a,b,c).

hanoi(N,_,_,_).

hanoi(N,fromPin,ToPin,UsingPin):-M is N-1,N>1.

hanoi(M,FromPin,UsingPin,ToPin).

move(FromPin,FromPin).

hanoi(M,ToPin,FromPin,UsingPin).

move(From,To):-write([move,disk,from,pin,from,to,pin,ToPin]).

?-hanoi(N,FromPin,ToPin,UsingPin).

Output:

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

Mrinalini Rana CSE7th sem 685034228

Program:

factorial(0,1).

factorial(X,Y) :-

X1 is X - 1,

factorial(X1,Z),

Y is Z*X,!.

?- factorial(15,X),write(X).

Output:

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

Mrinalini Rana CSE7th sem 685034228

Program:

member(X,[X|R]).

member(X,[Y|R]) :- member(X,R).

?- member(2,[1,2,3]).

Output:

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

Mrinalini Rana CSE7th sem 685034228

Program:

fib(1,1).

fib(2,1).

fib(N,R):- N >= 3,N1 is N-1,N2 is N-2,

fib(N1,R1),fib(N2,R2),R is R1+R2.

?- fib(7,R),write(R).

Output:

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

Mrinalini Rana CSE7th sem 685034228

PROGRAM:

sum_to(1,1).

sum_to(N,R):- N\=1,

N1 is N-1,

sum_to(N1,R1),

R is N+R1.

?-sum_to(6,X),write(X).

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

Mrinalini Rana CSE7th sem 685034228

Output:

Program:

aless(advocate,clergyman).

?-aless (advocate,clergyman).

Output:

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

Mrinalini Rana CSE7th sem 685034228

Program:

boy(rohan).

boy(krishana).

boy(paul).

girl(ritika).

girl(komal).

girl(ridhima).

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

Mrinalini Rana CSE7th sem 685034228

possible_pair(X,Y):-boy(X),girl(Y).

?-possible_pair(X,Y),write(X),write(Y).

Output:

Program:

change(you,i).

change(are,[am,not]).

change(frence,german).

change(do,no).

change(X,X).

alter([],[]).

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

Mrinalini Rana CSE7th sem 685034228

alter([H|T],[X|Y]):-change(H,X),alter(T,Y).

?-alter([you,are,a,computer],Z),write(Z).

Output:

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

- Arabic TranscriptionTransféré parwaa2000
- Mini ProjectTransféré parLimunga Jemea
- Matching SHIQ OntologiesTransféré parijcsis
- confdltBojanczyk09Transféré parAftab Saad
- class notes on IOS.docxTransféré parVenugopal Mantraratnam
- Menzel TheTrueModalLogicTransféré parGuillermo García
- formal methodTransféré parAlvin Shin
- edge onTransféré parLalithe
- Introduction to PrologTransféré parWan Hussain Wan Ishak
- The Bell and LaPadula Security model.pdfTransféré parJuan Sebastián Restrepo Ángel
- logic of exceptionTransféré parrefutationofcantor
- Klimovsky Axiomatica resumen.pdfTransféré parEsteban Benetons
- Prolog-2Transféré parvini_upmanyu
- Disputatio Vol. IV No. 34 Logic Norms and Ontology2Transféré parcarlosjesusandre
- Discrete Math and Functional ProgrammingTransféré parglobuous
- WHAT IS TEMPORAL ONTOLOGY.pdfTransféré parMarx Jose Gomez Liendo

- yandexTransféré parFaizan Ishfaq
- Derrida and Formal Logic - PaperTransféré parJose Dehilario
- PCDTransféré parBhaskar Padmanabhan
- Peano ArithmeticTransféré parglaufan
- Lexical and Syntax AnalysisTransféré parrtarak
- bpj lesson 7-2Transféré parapi-307094458
- Named Entity Recognition for Question AnsweringTransféré parFajar Wicaksono
- 8Ai Question BankTransféré parRigobert Ngeleja
- smt08Transféré parzegulas
- 2. Context Free GrammarsTransféré parjun71178
- Class7_Pumping Lemma ExamplesTransféré parNavneet Kumar
- AI-2MARKS-2Transféré parNirmala Durai
- Discrete Math Review Sheet (Exam 1)Transféré parJ R
- Pcd - Lab ManualTransféré parDhamodharan Veeraperumal
- Taylor Chap 3 Linear ProgrammingTransféré parAnnisa Nurul
- Turbo BMTransféré parSukmana Mlq
- Koyre - Liar.pdfTransféré parDjepeto
- Strings IO Formatting ParsingTransféré parPradeep Tiwari
- Guarded commands. non-determinacy and a calculus for the derivation of programs, by Edsger W.DijkstraTransféré parxorxpto
- Java and Regular ExpressionsTransféré parrxdravi
- Metalua ManualTransféré parAnthony John Sherbondy
- Conceptions of Truth in Intuitionism[1]Transféré parCamila Jourdan
- Mathematical ModelTransféré parzxmin
- Toc 3Transféré parapi-3696125
- mamdani sugenoTransféré parNoormalita Irviana
- Numbertrick SlidesTransféré parAzratee Zawawi
- 15. Comp Sci - Ijcseitr -Realization of Arithmetic Operations - u.m.fernandes DimloTransféré parTJPRC Publications
- Rr310505 Principles of Programming LanguagesTransféré parSrinivasa Rao G
- 106101002Transféré parHarsh Vardhan Pundhir
- CD_R13_UNIT I_JNTUKTransféré parmanjusha