top of page # Market Research Group

Public·6 members

## Logic Programming and Prolog

Logic programming is a paradigm of programming that uses logic as the basis for computation. Logic programming languages allow programmers to express problems and solutions in terms of facts, rules, and queries, rather than low-level instructions. In this article, we will explore the concepts and features of logic programming, as well as one of the most popular logic programming languages: Prolog.

## What is logic programming?

Logic programming is a style of programming that uses mathematical logic to represent and manipulate knowledge. Logic programming languages are based on the idea that a program is a set of logical statements that describe the properties and relations of entities in a problem domain. A computation is performed by applying logical inference to these statements, in order to answer queries or derive new facts.

### Features of logic programming

Some of the main features of logic programming are:

• Declarative: Logic programming languages are declarative, which means that they focus on what the problem is, rather than how to solve it. The programmer specifies the facts and rules that define the problem domain, and the language handles the details of how to search for solutions.

• Relational: Logic programming languages are relational, which means that they use relations (also called predicates) to represent data and knowledge. A relation is a set of tuples that satisfy a certain condition. For example, the relation parent(X,Y) represents the set of all pairs (X,Y) such that X is a parent of Y.

• Rule-based: Logic programming languages are rule-based, which means that they use rules to define the logical consequences of facts. A rule is a statement of the form "if A then B", where A and B are logical expressions. For example, the rule grandparent(X,Z) :- parent(X,Y), parent(Y,Z) defines the relation grandparent(X,Z) in terms of the relations parent(X,Y) and parent(Y,Z).

• Backward chaining: Logic programming languages use backward chaining as the main method of inference. Backward chaining is a technique that starts from a query (or a goal) and tries to find facts and rules that support it. For example, to answer the query grandparent(alice,bob), the language would look for facts and rules that match the pattern grandparent(alice,bob), such as grandparent(alice,bob) :- parent(alice,charlie), parent(charlie,bob).

### Applications of logic programming

Logic programming has many applications in various fields, such as:

• Artificial intelligence: Logic programming is widely used for artificial intelligence tasks, such as natural language processing, knowledge representation, reasoning, planning, expert systems, etc.

• Databases: Logic programming can be used for querying and manipulating data in relational databases, as well as for designing and implementing database systems.

• Symbolic computation: Logic programming can be used for performing symbolic manipulation of mathematical expressions, such as algebra, calculus, logic, etc.

• Software engineering: Logic programming can be used for developing software tools, such as compilers, debuggers, testing frameworks, etc.

## What is Prolog?

Prolog is one of the most widely used logic programming languages. Prolog stands for programming in logic. Prolog was designed by Alain Colmerauer and Philippe Roussel at the University of Marseille, France, in 1972, based on the ideas of Robert Kowalski at the University of Edinburgh, UK. Prolog is intended primarily as a declarative programming language, where the program logic is expressed in terms of relations, facts, and rules. A computation is initiated by running a query over these relations.

### History of Prolog

Prolog has its roots in first-order logic, a formal logic that is used to express statements and arguments in mathematics and philosophy. First-order logic consists of terms (such as constants, variables, and functions) and formulas (such as atoms, negations, conjunctions, disjunctions, implications, and quantifiers). First-order logic can be used to define the syntax and semantics of natural languages, as well as to reason about the properties and relations of objects and concepts.

In the late 1960s and early 1970s, several researchers explored the idea of using first-order logic as a programming language. One of them was Robert Kowalski, who proposed a procedural interpretation of Horn clauses, a subset of first-order logic that consists of formulas of the form "head :- body", where head and body are conjunctions of atoms. Kowalski showed that Horn clauses can be used to represent both data and procedures, and that logical inference can be used to execute programs.

Another researcher was Alain Colmerauer, who developed a natural language processing system called Q-systems, which used a variant of first-order logic called clausal form. Colmerauer wanted to create a language that could handle natural language input and output, as well as perform logical reasoning. He collaborated with Philippe Roussel, who implemented a prototype interpreter for clausal form. They named their language Prolog, which was an acronym for programmation en logique (programming in logic).

The first version of Prolog was implemented in 1972 on an IBM 360/44 computer. It had about 300 lines of assembly code and could handle about 50 relations. The first application of Prolog was to translate sentences between French and English. Later versions of Prolog added features such as lists, arithmetic operations, input/output facilities, etc. Prolog soon gained popularity among researchers and practitioners in artificial intelligence and computational linguistics.

### Syntax and semantics of Prolog

Prolog has a simple and elegant syntax that is based on first-order logic. Prolog has only one data type: the term. A term can be one of the following:

• An atom: An atom is a symbolic constant that represents a name or an identifier. An atom can be any sequence of alphanumeric characters that starts with a lowercase letter or any sequence of characters enclosed in single quotes. For example, alice, 'Hello world', x_1 are atoms.

• A variable: A variable is a symbolic name that can be bound to any term during execution. A variable can be any sequence of alphanumeric characters that starts with an uppercase letter or an underscore. For example, X, Y, _Z are variables.

• A compound term: A compound term is a term that consists of an atom (called the functor) followed by a sequence of terms (called the arguments) enclosed in parentheses. The number of arguments is called the arity of the compound term. For example, parent(alice,bob), +(2,3), sin(X) are compound terms.

• A number: A number is a term that represents a numerical value. Prolog supports two types of numbers: integers and floats. For example, 42, -3, 3.14 are numbers.

A Prolog program consists of a set of clauses. A clause can be one of the following:

• A fact: A fact is a clause that consists of a single atomic or compound term followed by a period. A fact represents a relation that is always true. For example, parent(alice,bob). is a fact that states that alice is a parent of bob.

• A rule: A rule is a clause that consists of an atomic or compound term (called the head) followed by ":-" (read as "if") and a sequence of terms (called the body) separated by commas and followed by a period. A rule represents a relation that is true if the body is true. For example, grandparent(X,Z) :- parent(X,Y), parent(Y,Z). is a rule that states that X is a grandparent of Z if X is a parent of Y and Y is a parent of Z.

## How to use Prolog?

To use Prolog, you need to have a Prolog compiler installed on your computer. A Prolog compiler is a program that translates Prolog code into executable code that can run on your machine. There are many Prolog compilers available, both free and commercial. Some of the most popular ones are:

• SWI-Prolog: SWI-Prolog is a comprehensive and robust free Prolog environment that supports many features and libraries. It is widely used in research, education, and industry. It runs on Windows, Linux, MacOS, and other platforms. You can download it from https://www.swi-prolog.org/.

• GNU Prolog: GNU Prolog is a free Prolog compiler that conforms to the ISO standard for Prolog. It also supports constraint logic programming and interfaces with C and Java. It runs on Windows, Linux, MacOS, and other platforms. You can download it from http://www.gprolog.org/.

### Writing Prolog programs

To write a Prolog program, you need to create a text file with the extension .pl (for example, hello.pl) and write your clauses in it. You can use any text editor of your choice, such as Notepad, Vim, Emacs, etc. You can also use an integrated development environment (IDE) that provides syntax highlighting, code completion, debugging tools, etc. Some of the IDEs for Prolog are Visual Prolog, Eclipse CLP, and Ciao.

A typical Prolog program consists of three parts: a directive, a knowledge base, and a query.

• A directive is a clause that starts with ":-" and instructs the compiler how to process the program. For example, :- dynamic parent/2. is a directive that tells the compiler that the relation parent/2 can be modified during execution.

• A knowledge base is a set of facts and rules that define the problem domain. For example, parent(alice,bob). and grandparent(X,Z) :- parent(X,Y), parent(Y,Z). are clauses that belong to the knowledge base.

• A query is a clause that starts with ":-" and asks a question to the knowledge base. For example, :- grandparent(alice,bob). is a query that asks whether alice is a grandparent of bob.

### Running Prolog queries

To run a Prolog query, you need to load your program into the Prolog compiler and enter your query at the prompt. The Prolog compiler will try to find all possible solutions to your query by applying logical inference to your knowledge base. If it finds a solution, it will display it on the screen and ask you if you want more solutions. You can type ";" (semicolon) to ask for more solutions or "." (period) to stop. If there are no more solutions or if there is no solution at all, it will display "false." or "no." respectively.

For example, suppose you have a file called family.pl that contains the following clauses:

:- dynamic parent/2. parent(alice,bob). parent(bob,charlie). parent(charlie,david). grandparent(X,Z) :- parent(X,Y), parent(Y,Z).

To run a query on this file, you can do the following:

• Open the Prolog compiler of your choice (for example, SWI-Prolog or GNU Prolog).

• Load the file into the compiler by typing consult('family.pl'). at the prompt. You should see a message like "family.pl compiled 0.00 sec, 4 clauses".

• Enter your query at the prompt. For example, type grandparent(alice,charlie). and press Enter. You should see a message like "true ;" or "Yes". This means that the query is true and there may be more solutions.

• Type ";" and press Enter to ask for more solutions. You should see a message like "false." or "No". This means that there are no more solutions.

• Type "." and press Enter to stop. You should see the prompt again.

## Examples of Prolog programs

To illustrate how to write and run Prolog programs, we will present three simple examples: a hello world program, a family tree program, and a list operations program.

### Hello world program

A hello world program is a program that prints the message "Hello world" on the screen. It is often used as a first program to test the installation and configuration of a programming language. Here is how to write and run a hello world program in Prolog:

• Create a file called hello.pl and write the following clause in it:

:- write('Hello world').

• Open the Prolog compiler of your choice and load the file by typing consult('hello.pl'). at the prompt.

• Type write('Hello world'). at the prompt and press Enter. You should see the message "Hello world" on the screen.

### Family tree program

A family tree program is a program that represents and manipulates information about family relationships. It is often used as an example of how to use facts and rules in Prolog. Here is how to write and run a family tree program in Prolog:

• Create a file called family.pl and write the following clauses in it:

:- dynamic parent/2. parent(alice,bob). parent(bob,charlie). parent(charlie,david). grandparent(X,Z) :- parent(X,Y), parent(Y,Z). sibling(X,Y) :- parent(Z,X), parent(Z,Y), X \= Y. ancestor(X,Y) :- parent(X,Y). ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y).

• Open the Prolog compiler of your choice and load the file by typing consult('family.pl'). at the prompt.

• Type some queries at the prompt and press Enter. For example, you can type:

• parent(alice,bob). to ask whether alice is a parent of bob. You should see "true ;" or "Yes".

• sibling(bob,charlie). to ask whether bob is a sibling of charlie. You should see "false." or "No".

• ancestor(alice,david). to ask whether alice is an ancestor of david. You should see "true ;" or "Yes".

• sibling(X,Y). to ask who are siblings in the family. You should see something like "X = bob, Y = charlie ;" or "bob charlie Yes". This means that bob and charlie are siblings and there may be more solutions.

• ancestor(X,Y). to ask who are ancestors in the family. You should see something like "X = alice, Y = bob ;" or "alice bob Yes". This means that alice is an ancestor of bob and there may be more solutions.

### List operations program

A list operations program is a program that performs some common operations on lists, such as appending, reversing, sorting, etc. It is often used as an example of how to use recursion and pattern matching in Prolog. Here is how to write and run a list operations program in Prolog:

• Create a file called list.pl and write the following clauses in it:

append([],L,L). append([HT],L,[HR]) :- append(T,L,R). reverse([],[]).

H],R). sort([],[]). sort([HT],S) :- sort(T,S1), insert(H,S1,S). insert(X,[],[X]). insert(X,[HT],[X,HT]) :- X = H, insert(X,T,R).

• Open the Prolog compiler of your choice and load the file by typing consult('list.pl'). at the prompt.

• Type some queries at the prompt and press Enter. For example, you can type:

• append([a,b,c],[d,e,f],L). to ask what is the result of appending the lists [a,b,c] and [d,e,f]. You should see something like "L = [a,b,c,d,e,f] ;" or "[a,b,c,d,e,f] Yes". This means that the result is [a,b,c,d,e,f] and there is no more solution.

• reverse([a,b,c],L). to ask what is the result of reversing the list [a,b,c]. You should see something like "L = [c,b,a] ;" or "[c,b,a] Yes". This means that the result is [c,b,a] and there is no more solution.

• sort([3,1,4,2],L). to ask what is the result of sorting the list [3,1,4,2]. You should see something like "L = [1,2,3,4] ;" or "[1,2,3,4] Yes". This means that the result is [1,2,3,4] and there is no more solution.

• append(X,Y,[a,b,c]). to ask what are the possible values of X and Y that can be appended to form the list [a,b,c]. You should see something like "X = [], Y = [a,b,c] ;" or "[] [a,b,c] Yes". This means that one possible solution is X = [] and Y = [a,b,c] and there may be more solutions.

• reverse(L,[a,b,c]). to ask what are the possible values of L that can be reversed to form the list [a,b,c]. You should see something like "L = [c,b,a] ;" or "[c,b,a] Yes". This means that one possible solution is L = [c,b,a] and there is no more solution.

• sort(L,[1,2,3]). to ask what are the possible values of L that can be sorted to form the list [1,2,3]. You should see something like "L = [1,2,3] ;" or "[1,2,3] Yes". This means that one possible solution is L = [1,2,3] and there may be more solutions.

## Conclusion

In this article, we have learned about logic programming and Prolog. We have seen how logic programming uses facts and rules to represent and manipulate knowledge, and how Prolog uses terms and clauses to express logic programming concepts. We have also seen how to install and use Prolog compilers, and how to write and run Prolog programs. We have explored some examples of Prolog programs that demonstrate the power and elegance of logic programming.

Logic programming and Prolog are useful tools for solving problems that involve symbolic reasoning and natural language processing. They can also be used for other domains that require declarative and relational programming. Logic programming and Prolog are not only interesting from a theoretical perspective, but also from a practical one. They can help you develop your logical thinking skills and your creativity as a programmer.

## FAQs

• Q: What are the differences between logic programming and functional programming?

• A: Logic programming and functional programming are both declarative paradigms of programming that use mathematical concepts as the basis for computation. However, they differ in several aspects. Logic programming uses logic as the foundation, while functional programming uses functions as the foundation. Logic programming uses relations, facts, rules, and queries as the main constructs, while functional programming uses expressions, values, functions, and types as the main constructs. Logic programming uses backward chaining as the main method of inference, while functional programming uses evaluation as the main method of computation.

• Q: What are the differences between Prolog and Datalog?

A: Prolog and Datalog are both logic programming languages that use Horn clauses as the main construct. However, they differ in several aspects. Prolog is a general-purpose language that supports many features and libraries, while Datalog is a domain-specific language that is mainly used for querying and manipulating relational databases. Prolog allows arbitrary terms and functions as arguments of predicates, while Datalog only allows constants and variables as arguments of predicates. Prolog allows arithmetic operations and input/output facilities, while Datalog does not. Prolog uses depth-first search as the main search strategy, while Datalog uses bottom