SLLP

45
INSTITUTE OF ENGINEERING AND TECHNOLOGY BHADDAL, ROPAR PRACTICAL FILE SLLP-LAB (CS-416) SUBMITTED TO : SUBMITTED BY : Ms. Amandeep Kaur

Transcript of SLLP

Page 1: SLLP

INSTITUTE OF ENGINEERING AND TECHNOLOGY BHADDAL,

ROPAR

PRACTICAL FILESLLP-LAB

(CS-416)

SUBMITTED TO: SUBMITTED BY:

Ms. Amandeep Kaur

Page 2: SLLP

INDEXINDEX

Sr.No.Sr.No. Name Of The ExperimentName Of The Experiment PagePage No.No.

1.1. Study of Propositional Logic.Study of Propositional Logic. 1.1.

2.2. Study of First Order Predicate Logic.Study of First Order Predicate Logic. 5.5.

3.3. Study of Execution Model of PROLOG and how Recursion works in PROLOG.

8.8.

4.4. Study of some Built-in predicates. 9.9.

5.5. Introduction to Prolog programming by a simple Prolog Introduction to Prolog programming by a simple Prolog program.program.

10.10.

6.6. Program to find whether the given number is positive or Program to find whether the given number is positive or negative.negative.

13.13.

7.7. Program to find whether the given number is even or odd.Program to find whether the given number is even or odd. 14.14.

8.8. Program to check whether a given person is member of club or Program to check whether a given person is member of club or not.not.

15.15.

9.9. Program showing mapping that is constructing new structure Program showing mapping that is constructing new structure similar to old one. similar to old one.

16.16.

10.10. (i)(i) Program to find length of the list using Recursion.Program to find length of the list using Recursion.(ii)(ii) Program to find length of the list using Accumulators.Program to find length of the list using Accumulators.

17.17.

11.11. Program to find the factorial of the number.Program to find the factorial of the number. 19.19.

12.12. Program to generate Fibonacci Series.Program to generate Fibonacci Series. 20.20.

13.13. Program to illustrate the use of recursion to find out sum of N Program to illustrate the use of recursion to find out sum of N natural numbers.natural numbers.

21.21.

14.14. Program to illustrate Cut and Cut-Fail combination in Prolog.Program to illustrate Cut and Cut-Fail combination in Prolog. 22.22.

15.15. Program to describe some basic predicates that is useful for Program to describe some basic predicates that is useful for manipulating Lists.manipulating Lists.

(i)(i) To concatenate two Lists.To concatenate two Lists.(ii)(ii) To delete element from the List.To delete element from the List.(iii)(iii) To reverse elements of the List.To reverse elements of the List.(iv)(iv) To perform union operation on two Lists.To perform union operation on two Lists.(v)(v) To perform intersection operation on two Lists. To perform intersection operation on two Lists.

23.23.

16.16. Program to implement bubble sort.Program to implement bubble sort. 28.28.

17.17. Program to implement intersection sort.Program to implement intersection sort. 29.29.

18.18. Program to implement Tick-Tack-Toe Game.Program to implement Tick-Tack-Toe Game. 30.30.

Page 3: SLLP

Experiment No.:1Study of Propositional Logic

Introduction

Propositional logic, also known as sentential logic, is that branch of logic that studies ways of combining or altering statements or propositions to form more complicated statements or propositions. 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. Propositional logic largely involves studying logical connectives such as the words "and" and "or" and the rules determining the truth-values of the propositions they are used to join, as well as what these rules mean for the validity of arguments, and such logical relationships between statements as being consistent or inconsistent with one another, as well as logical properties of propositions, such as being tautologically true, being contingent, and being self-contradictory. Propositional logic also studies way of modifying statements, such as the addition of the word "not" that is used to change an affirmative statement into a negative statement. Here, the fundamental logical principle involved is that if a given affirmative statement is true, the negation of that statement is false and if a given affirmative statement is false, the negation of that statement is true.Propositional logic can be thought of as primarily the study of logical operators. A logical operator is any word or phrase used either to modify one statement to make a different statement, or join multiple statements together to form a more complicated statement. In English, words such as "and", "or", "not", "if ... then...", "because", and "necessarily", are all operators.

A logical operator is said to be truth-functional if the truth-values (the truth or falsity, etc.) of the statements it is used to construct always depend entirely on the truth or falsity of the statements from which they are constructed. The English words "and", "or" and "not" are (at least arguably) truth-functional, because a compound statement joined together with the word "and" is true if both the statements so joined are true, and false if either or both are false, a compound statement joined together with the word "or" is true if at least one of the joined statements is true, and false if both joined statements are false, and the negation of a statement is true if and only if the statement negated is false.

Truth-functional propositional logic is that branch of propositional logic that limits itself to the study of truth-functional operators. Classical (or "bivalent") truth-functional propositional logic is that branch of truth-functional propositional logic that assumes that there are only two possible truth-values a statement (whether simple or complex) can have: (1) truth, and (2) falsity, and that every statement is either true or false but not both.

Classical truth-functional propositional logic is by far the most widely studied branch of propositional logic, and for this reason, most of the remainder of this article focuses exclusively on this area of logic. In addition to classical truth-functional propositional logic, there are other branches of propositional logic that study logical operators, such as "necessarily", that are not truth-functional. There are also "non-classical" propositional logics in which such possibilities as (i) a proposition's having a truth-value other than truth or falsity, (ii) a proposition's having an indeterminate truth-value or lacking a truth-

Page 4: SLLP

value altogether, and sometimes even (iii) a proposition's being both true and false, are considered.

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

Paris is the capital of France and Paris has a population of over two million. Therefore, Paris has a population of over two million.

If we use the letter 'C' as our translation of the statement "Paris is the capital of France" in PL, and the letter 'P' as our translation of the statement "Paris has a population of over two million", and use a horizontal line to separate the premise(s) of an argument from the conclusion, the above argument could be symbolized in language PL as follows:

Definition: A statement letter of PL is defined as any uppercase letter written with or without a numerical subscript.

Definition: A connective or operator of PL is any of the signs '¬', '&', 'v', '→', and '↔'.

Definition: A well-formed formula (hereafter abbreviated as wff) of PL is defined recursively as follows:

1. Any statement letter is a well-formed formula. 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.

b) Truth Functions and Truth Tables

Conjunction: The conjunction of two statements α and β, written in PL as (α & β) , is true if both α and β are true, and is false if either α is false or β is false or both are false.

Page 5: SLLP

α β (α & β)

TTFF

TFTF

TFFF

Disjunction: The disjunction of two statements α and β, written in PL as (α v β) , is true if either α is true or β is true, or both α and β are true, and is false only if both α and β are false.

α β (α v β)

TTFF

TFTF

TTTF

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:

α β (α → β)

TTFF

TFTF

TFTT

Material Equivalence: This truth-function is represented in language PL with the sign '↔'. A statement of the form (α ↔ β) is regarded as true if α and β both are either true or false, and is regarded as false if they have different truth-values. Hence, we have the following chart:

α β (α ↔ β)

TTFF

TFTF

TFFT

Negation: The negation of statement α, simply written ¬α in language PL, is regarded as 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:

Α ¬α

TF

FT

Page 6: SLLP

Consider a combined truth table for the wffs "¬P → ¬Q" and "¬(Q & ¬P)":

P Q | ¬ P → ¬ Q ¬ (Q & ¬ P))

TFTF

FFTT

TTFF

TTFT

FTFT

TFTF

TTFT

TFTF

FFTF

FFTT

TTFF

Page 7: SLLP

Experiment No.:2Study of First Order Predicate Logic

Introduction

First-order logic (FOL) is a language in symbolic science, which is used by mathematicians, philosophers, linguists, and computer scientists. It goes by many names, including: first-order predicate calculus (FOPC), the lower predicate calculus, the language of first-order logic or predicate logic. The most used name is however FOL, pronounced ef-oh-el. FOL is a system of deduction extending propositional logic by the ability to express relations between individuals (e.g. people, numbers, and "things") more generally.

Propositional logic is not adequate for formalizing valid arguments that rely on the internal structure of the propositions involved. For example, a translation of the valid argument

All men are mortal Socrates is a man Therefore, Socrates is mortal

which is invalid. The rest of the article explains how FOL is able to handle these sorts of arguments.

The atomic sentences of first-order logic have the form P(t1, ..., tn) (a predicate with one or more "arguments") rather than being propositional letters as in propositional logic. This is usually written without parentheses or commas, as below

The new ingredient of first-order logic not found in propositional logic is quantification: where φ is any (well-formed) formula, the new constructions ∀x φ and ∃x φ — read "for all x, φ" and "for some x, φ" — are introduced, where x is an individual variable whose range is the set of individuals of some given universe of discourse (or domain). For example, if the universe consists solely of people, then x ranges over people. For convenience, we write φ as φ(x) to show that it contains only the variable x free and, for b a member of the universe, we let φ[b] express that b satisfies (i.e. has the property expressed by) φ. Then ∀x φ(x) states that φ[b] is true for every b in the universe, and ∃x φ(x) means that there is a b (in the universe) such that φ[b] holds.

The argument about Socrates can be formalized in first-order logic as follows. Let the universe of discourse be the set of all people, living and deceased and let Man(x) be a predicate (which, informally, means that the person represented by variable x is a man) and Mortal(x) be a second predicate. Then the argument above becomes

∀ x (Man(x) → Mortal(x)) Man(Socrates) ∴ Mortal(Socrates)

A literal translation of the first line would be "For all x, if x is described by 'Man', x must also be described by 'Mortal'." The second line states that the predicate "Man" applies to Socrates, and the third line translates to "Therefore, the description 'Mortal' applies to Socrates."

Page 8: SLLP

Defining first-order logic

A predicate calculus consists of:-

formation rules (i.e. recursive definitions for forming well-formed formulas). transformation rules (i.e. inference rules for deriving theorems). axioms or axiom schemata (possibly countable infinite).

The axioms considered here are logical axioms which are part of classical FOL. Further, non-logical axioms are added to yield specific first-order theories that are based on the axioms of classical FOL (and hence are called classical first-order theories, such as classical set-theory). The axioms of first-order theories are not regarded as truths of logic per se, but rather as truths of the particular theory that usually has associated with it an intended interpretation of its non-logical symbols. (See an analogous idea at logical versus non-logical symbols.) Classical FOL does not have associated with it an intended interpretation of its non-logical vocabulary (except arguably a symbol denoting identity, depending on whether one regards such a symbol as logical).

When the set of axioms is infinite, it is required that there be an algorithm which can decide for a given well-formed formula whether or not it is an axiom. There should also be an algorithm which can decide whether a given application of an inference rule is correct or not.It is important to note that FOL can be formalized in many equivalent ways; there is nothing canonical about the axioms and rules of inference given here. There are infinitely many equivalent formalizations all of which yield the same theorems and non-theorems, and all of which have equal right to the title 'FOL'.

Vocabulary

The "vocabulary" is composed of

1. A set of predicate variables (or relations) each with some valence (or arity) ≥1, which are often denoted by uppercase letters P, Q, R....

2. A set of constants, often denoted by lowercase letters at the beginning of the alphabet a, b, c....

3. A set of functions, each of some valence ≥ 1, which are often denoted by lowercase letters f, g, h....

4. An infinite set of variables, often denoted by lowercase letters at the end of the alphabet x, y, z....

5. Symbols denoting logical operators (or connectives):

Logical And – V Logical Or - /\ Logical Not - ~ Logical Implication - Logical Biconditional -

6. Symbols denoting quantifiers: (universal quantification), (existential quantification).7. Left and Right parenthesis.8. An identity or equality symbol “=” is sometimes but not always included in the

vocabulary.

Page 9: SLLP

Experiment No.:3Study of Execution Model in PROLOG and how Recursion works

in PROLOG.

Execution Model: The execution of a Prolog Program consists of following three steps:- Development of a program. Compiling of a program. Linking of a program.

1) Development of a Program: Program consists of facts, rules and queries to the interpreter. Facts are always true (unconditionally). Rules (clauses) are in the form of syntax:-

<Head> :- <Tail> or Atom: - Atom1, Atom2,…..,Atomn.If Atom1,….,Atomn all are true, only then Atom is true otherwise false. Queries are the questions whose result is derived from the facts and rules and syntax is:-

?-Predicate 2) Compiling of a Program: When query is entered, the second stage of execution starts which is compiling of a program in which interpreter checks for the syntax errors. If there exists error, then it prompt the user, else it will change the source code into the object code.3) Linking of the Prolog Program: The linker checks for the linking error. If no error is found then the object code of the prolog program is changed into executable code.

Matching in Prolog during execution

For a perfect match to take place:- The predicate names and all the succeeding arguments must match. If the goal succeeds, then the interpreter leaves a marker by the fact where the goal

succeeded, to remind itself that the goal succeeded at this point in the database. The marker can be thought of as a notice board saying, e.g.:-

The goal planet(mercury). was satisfied at this point. It then reports success to the user by saying “Yes”. If goal fails, then the interpreter returns and says “No”.

Matching a simple query and facts:-If “?-orbits(the_moon,the_earth).” is the goal then the fact “orbits(the_moon,the_earth).” will result in a perfect match and the goal succeeds but the fact “orbits(the_moon,earth).” is a bad match and hence the goal fails.

Recursion: The recursion in any language is a function that can call itself until goal succeeds. In prolog, recursion appears when a predicate contains a goal that refers to itself. In Prolog and in any language, a recursive definition always has at least two parts. The first is a fact that acts like a slopping condition and the second is a rule that call itself simplified. At each level, the first fact is checked. If the fact is true, then the recursion ends. If not, the recursion continues. A recursive rule must never call itself with the same argument. If that happens, the program will never end.Example: Factorial. The best way in prolog to calculate a factorial is to do it recursively.

Page 10: SLLP
Page 11: SLLP

Experiment No.:4Study of some Built-in predicates.

By Built-in Predicates, we mean that the predicate’s definition is provided in advance by the Prolog system, instead of by your own clauses. Built-in predicates may provide facilities that cannot be obtained by definitions in pure Prolog. Or they may provide convenient facilities just to save each programmer from having to define them himself.Some of the Built-in predicates are defined below:-

1.consult(X): It is meant for those situations when you want the clauses in some file to augment those already in the database. The argument must be an atom giving the name of the file the clauses are to be taken from. E.g.:-

?- consult(myfile).

2.reconsult(X): It is same like consult except that the clauses read in are taken to supersede all existing clauses for the same predicate. Because of this, reconsult is appropriate for correcting programming mistakes.

3.true: This goal always succeeds. It is not actually necessary, as clauses and goals can be reordered or recombined to obviate any use of true. However, it exists for convenience.

4.fail: This goal always fails. There are two places where it is helpful. One place is the “cut fail” combination. Another place to use fail is where you explicitly want another goal to backtrack through all solutions.

5.asserta(X): It adds a clause at the beginning of the database. For this, X must be already instantiated to something representing a clause.

6.assertz(X): It is similar to asserta(X) but the difference is that it adds a clause at the end of the database.

7.retract(X): It enables a program to remove clauses from the database. The predicate takes a single argument, representing a term that the clause is to match. Once a clause has been removed it is never reinstated, even when backtracking tries to re-satisfy the retract goal.

8.not(X): The not(X) goal succeeds if an attempt to satisfy X fails. The not(X) goal fails if an attempt to satisfy X succeeds.

9.nl: It writes a control sequence to the current output stream that causes a “new line”. It succeeds only once.

10.write(X): This goal writes the term X to the current output stream. It succeeds only once.

11.cut: It allows you to tell Prolog which previous choices it need not consider again when it backtracks through the chain of satisfied goals. Syntactically, a use of “cut” in a rule looks just like the appearance of a goal which has the predicate “!” and no arguments. As a goal, this succeeds immediately and cannot be re-satisfied.12.var(X): The goal var(X) succeeds if X is currently an uninstantiated variable.Thus we would expect the following behavior. ?- var(X). Yes ?-var(23).

Page 12: SLLP

No ?- X = Y, Y=23, var(X). NoAn uninstantiated variable can represent part of a structure that has not yet been filled in.

13.nonvar(X): The goal nonvar(X0 succeeds if X is not currently an uninstantiated variable. The predicate nonvar is therefore the opposite of var.It could be defined in Prolog by:nonvar(X) :-var(X), ! , fail.nonvar( _ ) .

14.integer(X):The goal integer(X) succeeds if X is currently stands for an integer(a whole number)

15.arg(N,T,A):The predicate arg must always be used with its first two argument instantiated. It is used to access a particular argument of structure. The first argument of arg specifies which argument is required.The second specifies the structure thet the argument is to be found inside.Prolog finds the appropriate argument and then tries to match it with the third argument.

Page 13: SLLP

Experiment No.:5Introduction To Prolog Programming by a simple Prolog Program.

Prolog is a general purpose logic programming language associated with artificial intelligence and computational linguistics.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, represented as facts and rules. Execution is triggered by running queries over these relations. The first Prolog system was developed in 1972 by Alain Colmerauer and Philippe Roussel.Prolog was one of the first logic programming languages, and remains among the most popular such languages today, with many free and commercial implementations available. While initially aimed at natural language processing, the language has since then stretched far into other areas like theorem proving, expert systems, games, automated answering systems, ontologies and sophisticated control systems. Modern Prolog environments support the creation of graphical user interfaces, as well as administrative and networked applications.

Programming in Prolog

In Prolog, 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 screen. This permits the programmer to use some amount of conventional imperative programming when the logical paradigm is inconvenient. It has a purely logical subset, called "pure Prolog", as well as a number of extra logical features.

Data types

Prolog's single data type is the term. Terms are atoms, numbers, variables or compound terms.

An atom is a general-purpose name with no inherent meaning. Examples of atoms include x, blue, 'Taco', and 'some atom'.

Numbers can be floats or integers. Variables are denoted by a string consisting of letters, numbers and underscore characters,

and beginning with an upper-case letter or underscore. Variables closely resemble variables in logic in that they are placeholders for arbitrary terms.

A compound term is composed of an atom called a "functor" and a number of "arguments", which are again terms. Compound terms are ordinarily written as a functor followed by a comma-separated list of argument terms, which is contained in parentheses. The number of arguments is called the term's arity. An atom can be regarded as a compound term with arity zero. Examples of compound terms are truck_year('Mazda', 1986) and 'Person_Friends'(zelda,[tom,jim]).

Page 14: SLLP

Special cases of compound terms:A List is an ordered collection of terms. It is denoted by square brackets with the terms separated by commas or in the case of the empty list, []. For example [1, 2, 3] or [red, green, blue]. Strings: A sequence of characters surrounded by quotes is equivalent to a list of (numeric) character codes, generally in the local character encoding or Unicode if the system supports Unicode.For example: "to be, or not to be".

Rules and facts

Prolog programs describe relations, defined by means of clauses. Pure Prolog is restricted to Horn clauses, a Turing-complete subset of first-order predicate logic. There are two types of clauses: Facts and rules. A rule is of the formHead :- Body.and is read as "Head is true if Body is true". A rule's body consists of calls to predicates, which are called the rule's goals. The built-in predicate ,/2 (meaning a 2-arity operator with name ,) denotes conjunction of goals, and ;/2 denotes disjunction. Conjunctions and disjunctions can only appear in the body, not in the head of a rule.Clauses with empty bodies are called facts. An example of a fact is:cat(tom).which is equivalent to the rule:cat(tom) :- true.The built-in predicate true/0 is always true.Given the above fact, one can ask:is tom a cat??- cat(tom).Yeswhat things are cats??- cat(X).X = tomDue to the relational nature of many built-in predicates, they can typically be used in several directions. For example, length/2 can be used to determine the length of a list (length(List, L), given a list List) as well as to generate a list skeleton of a given length (length(X, 5)), and also to generate both list skeletons and their lengths together (length(X, L)). Similarly, append/3 can be used both to append two lists (append(ListA, ListB, X) given lists ListA and ListB) as well as to split a given list into parts (append(X, Y, List), given a list List). For this reason, a comparatively small set of library predicates suffices for many Prolog programs. All predicates can also be used to perform unit tests: Queries can be embedded in programs and allow for automatic compile-time regression testing.As a general purpose language, Prolog also provides various built-in predicates to perform routine activities like input/output, using graphics and otherwise communicating with the operating system. These predicates are not given a relational meaning and are only useful for the side-effects they exhibit on the system. For example, the predicate write/1 displays a term on the screen.

Prolog Program

Program Code:

Domain: It includes declaration and initialization of variables.n=integer.

Page 15: SLLP

Predicate: It defines functions on the variables.fact(n,n).Clauses: It is used to represent body of the program using rules and facts.fact(0,1).fact(1,1).fact(N,R):- N>1,N1 is N - 1,fact(N1,R1),R is R1 * N.Goal: It is the final query passed to the Prolog and results are displayed in output window. ?-fact(4,X),write(X).

Output Window:

Page 16: SLLP

Experiment No.:6Write a Program to find out whether the number is even or odd.

Program Code:

N=integer.input(n).input(N):-N mod 2 = 0,write("no is even"),nl.input(N):-write("no is odd").

?-input(3).

Output:

Page 17: SLLP

Experiment No.:7Write a Program to find out whether the number is positive or

negative

Program Code:

N=integer.input(n).input(N):-N>0,write("no is positive"),nl.input(N):-N<0,write("no is negative").

?-input(3).

Output:

Page 18: SLLP

Experiment No.:8Write a Program to find out whether the person is the member of

the club or not.

Program Code:

X=integer.L=X*member(element,list).member(X,[X|_]).member(X,[_|T]):-member(X,T).

?-member(chandan,[chandan,charan.charru]).

Output:

Page 19: SLLP

Experiment No.:9Write a Program in Prolog showing Mapping that is constructing

new structure to similar to old one.

Program Code:

X=integer.L=X*change(element,element).alter(list,list).change(you,i).change(are,am).change(my,your).change(X,X).alter([],[]).alter([H|T],[X|Y]):-change(H,X),alter(T,Y).

?-alter(['you','are','my','freind'],X),write(X),nl.

Output:

Page 20: SLLP

Experiment No.:10(i) Write a Program to find out length of the list using Recursion.

Program Code:

X=integer.L=X*length(list,element).length([],0).length([H|T],N):-length(T,N1),N=N1+1.

?-length([1,2,3,4,5],X),write(X),nl.

Output:

Page 21: SLLP

(ii) Write a Program to find out length of the list using Accumulators.

Program Code:

X=integer.L=X*length(list,element).lengthacc(list,element,element).lengthacc([],0,0).lengthacc([H|T],A,N):-lengthacc(T,A1,N1),A=A1+1.

?-lengthacc([1,2,3,4,5],A,X),write(A),nl.

Output:

Page 22: SLLP

Experiment No.:11Write a Program to find out Factorial of a number using recursion.

Program Code:

N=integer.fact(n,n).fact(0,1).fact(1,1).fact(N,R):- N>1,N1 is N - 1,fact(N1,R1),R is R1 * N.

?-fact(4,X),write(X).

Output:

Page 23: SLLP

Experiment No.:12Write a Program to generate Fibonacci Series.

Program Code:

N=integer.fab(n,n).fab(0,0).fab(1,1).fab(N,R):-N > 1,N1 is N - 1,fab(N1,R1),N2 is N - 2, fab(N2,R2), R is R1 + R2.

?-fab(4,X),write(X).

Output:

Page 24: SLLP

Experiment No.:13Write a Program to illustrate the use of recursion to find out sum

of first of N natural numbers.

Program Code:

N=integer.sum(n,n).sum(0,0).sum(1,1).sum(N,R):-N > 1,N1 is N - 1,sum(N1,R1), R is R1 + N.

?-sum(4,X),write(X).

Output:

Page 25: SLLP

Experiment No.:14Write a Program to illustrate the use of Cut predicate and Cut-Fail

Combination in Prolog.

CUT PREDICATE

Program Code:

N=integer.Sum_to(n,n).Sum_to(N,1):- N=<1,!.Sum_to(N,Res):- n1 is N – 1,Sum_to(N1,Res1),Res is Res1 + N.

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

Output:

CUT-FAIL PREDICATE

Program Code:

likes(aarti,X):-mango(X),!,fail.likes(aarti,X):-fruit(X).fruit(X):-apple(X).fruit(X):-mango(X).fruit(X):-orange(X).apple(a).mango(b).orange(c).

?-likes(aarti,a).

Page 26: SLLP

Experiment No.:15Write a Program to describe some Basic Predicates that is useful of

Manipulating Lists.

(i) To concatenate two Lists.

Program Code:

N=integer.L=N*append(list,list,list).append([],L,L).append([X|L1],L2,[X|L3]):-append(L1,L2,L3).

?-append([1,2,3],[4,5],X),write(X),nl.

Output:

Page 27: SLLP

(ii) To delete element from the list.

Program Code:

X=integer.L=X*delete(element,list,list).delete(X,[X|T],T).delete(X,[H|T].[H|T1]):-delete(X,T,T1).

?-delete(2,[1,2,3,4,5],X),write(X),nl.

Output:

Page 28: SLLP

(iii) To reverse elements of the list.

Program Code:

X=integer.L=X*reverse(list,list).append(list,list,list).reverse([],[]).reverse([H|T],L):-reverse(T,Z),append(Z,[H],L).append([],L,L).append([X|L1],L2,[X|L3]):-append(L1,L2,L3).

?-reverse([1,2,3,4],X),write(X),nl.

Output:

Page 29: SLLP

(iv) To perform Union operation on two lists.

Program Code:

X=integer.L=X*union(list,list,list).member(element,list).union([],L,L).union([H|T1],L,T2):-member(H,L),!,union(T1,L,T2).union([H|T1],L,[H|T2]):-union(T1,L,T2).member(H,[H|_]).member(H,[_|T]):-member(H,T).

?-union([1,2,3,4],[5,6,7],X),write(X),nl.

Output:

Page 30: SLLP

(v) To perform Intersection operation on two lists.

Program Code:

X=integer.L=X*intersect(list,list,list).member(element,list).intersect([],_,[]).intersect([H|T1],L,[H|T2]):-member(H,L),!,intersect(T1,L,T2).intersect([_|T1],L,T2):-intersect(T1,L,T2).member(H,[H|_]).member(H,[_|T]):-member(H,T).

?-intersect([1,2,3,4,5,6],[5,6,7,1,3],X),write(X),nl.

Output:

Page 31: SLLP

Experiment No.:16Write a Program to implement Bubble Sort.

Program Code:

X=integer.L=X*bsort(list,list).swap(list,list).greater(element,element).bsort(L,S):-swap(L,L1),!,bsort(L1,S).bsort(S,S).swap([X,Y|T],[Y,X|T]):-greater(X,Y).swap([Z|T],[Z|T1]):-swap(T,T1).greater(X,Y):- X > Y.

?-bsort([2,5,1,8,3],X),write(X).

Output:

Page 32: SLLP

Experiment No.:17Write a Program to implement Insertion Sort.

Program Code:

X=integer.L=X*insort(list,list).insorth(element,list,list).order(element,element).insort([],[]).insort([H|T],M):-insort(T,N),insorth(H,N,M).insorth(H,[A|T],[A|M]):-order(A,H),!,insorth(H,T,M).insorth(H,T,[H|T]).order(P,Q):-P<Q.?-insort([2,5,1,8,3],X),write(X).

Output:

Page 33: SLLP

Experiment No.:18Write a Program to implement Tick-Tack-Toe Game.

Program Code:

retractall(board(_)),assert(board([_Z1,_Z2,_Z3,_Z4,_Z5,_Z6,_Z7,_Z8,_Z9])).mark(Player,[x|_],1,1):-var(X),X=Player.mark(Player,[_,x|_],2,1):-var(X),X=Player.mark(Player,[_,_,x|_],3,1):-var(X),X=Player.mark(Player,[_,_,_,x|_],1,2):-var(X),X=Player.mark(Player,[_,_,_,_,x|_],2,2):-var(X),X=Player.mark(Player,[_,_,_,_,_,x|_],3,2):-var(X),X=Player.mark(Player,[_,_,_,_,_,_,x|_],1,3):-var(X),X=Player.mark(Player,[_,_,_,_,_,_,_,x|_],2,3):-var(X),X=Player.mark(Player,[_,_,_,_,_,_,_,_,x|_],3,3):-var(X),X=Player.

move(P,(1,1),[X1|R],[P|R]):-var(X1).move(P,(2,1),[X1,X2||R],[X1,P|R]):-var(X2).move(P,(3,1),[X1,X2,X3|R],[X1,X2,P|R]):-var(X3).move(P,(1,2),[X1,X2,X3,X4|R],[X1,X2,X3,P|R]):-var(X4).move(P,(2,2),[X1,X2,X3,X4,X5|R],[X1,X2,X3,X4P|R]):-var(X5).move(P,(3,2),[X1,X2,X3,X4,X5,X6|R],[X1,X2,X3,X4,X5,P|R]):-var(X6).move(P,(1,3),[X1,X2,X3,X4,X5,X6,X7|R],[X1,X2,X3,X4,X5,X6,P|R]):-var(X7).move(P,(2,3),[X1,X2,X3,X4,X5,X6,X7,X8|R],[X1,X2,X3,X4,X5,X6,X7,P|R]):-var(X8).move(P,(3,3),[X1,X2,X3,X4,X5,X6,X7,X8,X9|R],[X1,X2,X3,X4,X5,X6,X7,X8,P|R]):-var(X9).

record(Player,,X,Y):-retract(board(B)),mark(Player,B,X,Y),assert(board(B)).

win([Z1,Z2,Z3|_],P):-Z1==P,Z2==P,Z3==P.win([_,_,_Z1,Z2,Z3|_],P):-Z1==P,Z2==P,Z3==P.win([_,_,_,_,_,_,Z1,Z2,Z3],P):-Z1==P,Z2==P,Z3==P.win([Z1,_,_Z2,_,_,Z3,_,_],P):-Z1==P,Z2==P,Z3==P.win([_,Z1,_,_,Z2,_,_,Z3_],P):-Z1==P,Z2==P,Z3==P.win([_,_,Z1,_,_,Z2,_,_,Z3],P):-Z1==P,Z2==P,Z3==P.win([Z1,_,_,_,Z2,_,_,_,Z3],P):-Z1==P,Z2==P,Z3==P.win([_,_,Z1,_,Z2,_,Z3,_,_],P):-Z1==P,Z2==P,Z3==P.

open([Z1,Z2,Z3|_],Player):-(var(Z1)|Z1==Player),(var(Z2)|Z2==Player),(var(Z3)|Z3==Player).open([_,_,_,Z1,Z2,Z3|_],Player):-(var(Z1)|Z1==Player),(var(Z2)|Z2==Player),(var(Z3)|Z3==Player).open([_,_,_,_,_,_,Z1,Z2,Z3],Player):-(var(Z1)|Z1==Player),(var(Z2)|Z2==Player),(var(Z3)|Z3==Player).

Page 34: SLLP

open([Z1,_,_,Z2,_,_,Z3,_,_],Player):-(var(Z1)|Z1==Player),(var(Z2)|Z2==Player),(var(Z3)|Z3==Player).open([_,Z1,_,_,Z2,_,_,Z3_],Player):-(var(Z1)|Z1==Player),(var(Z2)|Z2==Player),(var(Z3)|Z3==Player).open([_,_,Z1,_,_,Z2,_,_,Z3],Player):-(var(Z1)|Z1==Player),(var(Z2)|Z2==Player),(var(Z3)|Z3==Player).open([Z1,_,_,_,Z2,_,_,_,Z3],Player):-(var(Z1)|Z1==Player),(var(Z2)|Z2==Player),(var(Z3)|Z3==Player).open([_,_,Z1,_,Z2,_,Z3,_,_],Player):-(var(Z1)|Z1==Player),(var(Z2)|Z2==Player),(var(Z3)|Z3==Player).open([_,_,Z1,_,Z2,_,Z3,_,_],Player):-(var(Z1)|Z1==Player),(var(Z2)|Z2==Player),(var(Z3)|Z3==Player).

value(Board,100):-win(Board,o),!.value(Board,100):-win(Board,X),!.value(Board,E):-findall(o,open(Board,o),MAX),lenght(MAX,Emax)%#lines open to ofindall(x,open(Board,x),MIN),lenght(MIN,Emin), %#lines open to xE is Emax-Emin.search(Position,Depth,(Move,Value)):- alpha_beta(o,Depth,Position,-100,100,Move,Vlaue).alpha_beta(Player,0,Position,_Alpha,_Beta,_NoMove,Vlaue):-value(Positon,Value),spy(Player,Position,Value).alpha_beta(Player,D,Position,Alpha,Beta,Move,Value):-D>0,findall((X,Y),mark(Player,Position,X,Y),Moves),Alpha1 is -Beta,% max/minBeta1 is -Alpha,D1 is D-1,evaluate_and_choose(Player,Moves,Position,D1,Alpha1,Beta1,nil,Move,Value)).evaluate_and_choose(Player,[Move|Moves],Position,Alpha,Beta,Record,Best,Move):- move(Player,Move,Position,Position1),other_Player(Player,OtherPlayer),other_Player(OtherPlayer,D,Position1,Alpha,Beta,_OtherMove,Value),Value1 is -Value,cutoff(Player,Move,Value1,D,Alpha,Beta,Moves,Position,Record,BestMove),evaluate_and_choose(_Player,[],_Position,_D,Alpha,_Beta,Move,(Move,Alpha)).cutoff(_Player,Move,Value,_D,_Alpha,Beta,_Moves,_Position,_Record,(Move,Value)):-Value>=Beta,!.cutoff(Player,Move,Value,D,Alpha,Beta,Moves,Position,_Reacord,BestMove):-Alpha<Value,Value<Beta,!.evaluate_and_choose(Player,Moves,Positon,D,Value,Beta,Move,BestMove).cutoff(player,_Move,Value,D,Alpha,Beta,moves,Position,Record,BestMove):-Value=<Alpha,!,evaluate_and_choose(Player,Moves,Position,D,Alpha,Beta,Record,BestMove).other_Player(o,x).other_Player(x,o).spy(Player,Position,Value):-spy,!,write(Player),write(' '),write(Positin),write(' '),writeln(Value).spy(_,_,_).%do nothingh(X,Y):-record(x,X,Y),showBoard.c:-board(B),alpha_beta(o,2,B,-200,200,(X,Y),_Value),record(o,X,Y),

Page 35: SLLP

showBoard.showBoard:-board([Z1,Z2,Z3,Z4,Z5,Z6,Z7,Z8,Z9]),write(' '),mark(Z1),write(' '),mark(Z2),write(' '),mark(Z3),nl,write(' '),mark(Z4),write(' '),mark(Z5),write(' '),mark(Z6),nl,write(' '),mark(Z7),write(' '),mark(Z8),write(' '),mark(Z9),nl.

s:-showBoard.mark(X):-var(X),write('#).mark(X):-\+var(X),write(X).connect(Port):-tcp_socket(Socket),gethostname(Host), % local hosttcp_connect(Socket,Host:Port),tcp_open_socket(Socket,INs,OUTs),assert(connnectedReadStream(INs)),assert(connectedWriteStream(OUTs)).ttt:-connectedReadStream(IStream),read(IStream,(X,Y)),record(x,X,Y), board(B),alpha_beta(o,2,B,-200,200,(U.V),_Value),record(o,U,V), connectedWritwStream(OStream),write(OStream,(U,V)), nl(OStream),flush_output(OStream),ttt.