You are on page 1of 27

EXPERIMENT – 1

Introduction:
Prolog, which stands for "Programming in Logic," is a declarative programming language
commonly used in artificial intelligence and computational linguistics. Developed in the
1970s by Alain Colmerauer and Philippe Roussel, Prolog originated from the logic
programming paradigm, with its roots deeply embedded in formal logic and mathematical
reasoning.Unlike traditional imperative programming languages like C++ or Java, Prolog
focuses on the logical relationships between entities rather than the sequence of steps to
achieve a goal. Programs in Prolog are executed by a process called "logical inference,"
where the system derives solutions by matching rules and facts against a query.

History of Prolog:
Prolog's inception can be traced back to the work on logic programming by Robert Kowalski
and Alain Colmerauer in the early 1970s. It was further refined by Colmerauer and Roussel at
the University of Aix-Marseille, France. Prolog gained popularity in the academic and
research communities due to its elegant approach to problem-solving using logic and rule-
based systems. Over the years, Prolog has undergone several revisions and standardizations,
with the most prominent being the Edinburgh Prolog, which laid the groundwork for
subsequent implementations.

Features of Prolog:
1. Declarative Style: Prolog allows programmers to declare what needs to be achieved
rather than explicitly specifying how to achieve it. This promotes a higher level of
abstraction and simplifies problem-solving.

2. Pattern Matching: Prolog employs pattern matching extensively, allowing rules and
facts to be matched against queries, facilitating powerful search and inference
capabilities.

3. Backtracking: If Prolog encounters a dead-end while searching for a solution, it can


backtrack and explore alternative paths. This enables Prolog to find multiple solutions
to a problem.

4. Recursion: Prolog supports recursion as a fundamental mechanism for iteration and


problem decomposition.

5. Logical Variables: Variables in Prolog are logical variables, representing


placeholders for values that will be determined during execution. They differ from
variables in imperative languages in that they can be instantiated with different values
during backtracking.

1|Page
6. Unification: Central to Prolog's operation is the process of unification, which is the
process of finding substitutions for variables that make two logical expressions
equivalent. Unification is used extensively during query resolution and rule
application.

7. Horn Clauses: Prolog programs typically consist of Horn clauses, which are logical
implications in the form of a head and a body. The head represents the goal to be
achieved, and the body consists of conditions that must be satisfied for the goal to be
true.

Data Types in Prolog:


Prolog has a few fundamental data types:

- Atoms: Represent constants such as names, symbols, or identifiers. Atoms are written in
lowercase and enclosed in single quotes if they contain special characters or spaces.
If an atom contains special characters or spaces, it must be enclosed within single quotes.
Here are some examples of atoms in Prolog:
likes(john, pizza)
color('red')
animal(dog).
In these examples, likes, john, pizza, color, red, animal, and dog are all atoms representing
various entities or relationships.

-Numbers: Prolog supports integers and floating-point numbers.


-Variables: Variables are denoted by strings beginning with an uppercase letter or an
underscore.
-Terms: Terms are compound data structures made up of atoms, numbers, variables, or other
terms. They are constructed using functors and can represent complex relationships between
entities.

Basic Elements of Syntax:


Prolog programs consist of clauses, which can be facts or rules. Facts are statements that are
always true, while rules define relationships between entities. Clauses end with a period.
Here's a simple example:`

2|Page
human(socrates)
mortal(X) :- human(X).

In this example, "socrates" is a fact, stating that Socrates is human. The rule `mortal(X) :-
human(X).` defines that if X is human, then X is mortal.

Clauses in Prolog:
In Prolog, a clause is a fundamental unit of logic programming. Clauses are statements that
define relationships, properties, or logical implications within a Prolog program. There are
two main types of clauses in Prolog:
 Facts: Facts are simple statements that assert the truth of a relationship or property. A
fact in Prolog consists of a predicate, which represents the relationship or property,
followed by a list of arguments. Facts serve as the base knowledge upon which Prolog
programs operate.
 Rules: Rules are logical implications that define conditions or relationships. A rule in
Prolog consists of a head and a body. The head specifies the goal to be achieved,
while the body contains conditions that must be satisfied for the goal to be true. Rules
are used to infer new information or to guide the execution of Prolog programs.

Facts in Prolog:
In Prolog, facts are simple statements that assert the truth of a relationship or property. Facts
provide the base knowledge upon which Prolog programs operate. A fact in Prolog consists of
a predicate followed by a list of arguments enclosed in parentheses. The predicate represents
the relationship or property being asserted, while the arguments represent the entities
involved in the relationship. Facts serve as the foundation upon which logical inferences and
queries are made in Prolog programs.

Example of facts in Prolog:

In these examples, likes, age, and parent are predicates, while (john, pizza), (susan, 25),
and (bob, alice) are the arguments to those predicates.

Rules in Prolog:

3|Page
In Prolog, rules are logical implications that define conditions or relationships. A rule in
Prolog consists of a head and a body. The head specifies the goal to be achieved, while the
body contains conditions that must be satisfied for the goal to be true. Rules are used to infer
new information or to guide the execution of Prolog programs. They provide a way to encode
problem-solving strategies or logical inferences within a Prolog program.

Example of a rule in Prolog:

This rule states that "X is mortal if X is human". Here, mortal(X) is the head, and human(X)
is the body.
In summary, in Prolog, facts provide simple assertions about relationships or properties, rules
define logical implications or conditions, and clauses encompass both facts and rules, serving
as the basic building blocks of Prolog programs.

Predicates in Prolog:
In Prolog, a predicate is a fundamental concept representing a relationship, property, or
action. Predicates are used to define logical statements or rules within a Prolog program.
They are composed of a functor, which specifies the name of the predicate, and a number of
arguments enclosed in parentheses. Predicates play a central role in defining the logic and
structure of Prolog programs.
 Functor: The functor is the name of the predicate, which identifies the relationship or
property being asserted. It begins with a lowercase letter or an underscore, followed
by a sequence of letters, digits, or underscores. The functor uniquely identifies the
predicate within the Prolog program.
 Arguments: The arguments of a predicate represent the entities or values involved in
the relationship or action described by the predicate. Arguments can be variables,
constants, or complex terms. They provide the necessary information to evaluate or
satisfy the predicate.

Example of predicates in Prolog:

In these examples, likes, age, and parent are predicates, while (john, pizza), (susan, 25),
and (bob, alice) are the arguments to those predicates.

4|Page
Queries in Prolog:
In Prolog, a query is a request for information or a solution to a logical problem posed to the
Prolog interpreter. Queries allow users to interact with Prolog programs by asking questions
or making logical inquiries. A query consists of a goal, which is a predicate followed by a list
of arguments enclosed in parentheses. The Prolog interpreter attempts to find solutions or
bindings for the variables in the query that satisfy the predicates and rules defined in the
program.
 Goal: The goal of a query is to determine whether a particular predicate or set of
predicates holds true given the current knowledge base and rules defined in the Prolog
program. The goal specifies the desired outcome or condition that the Prolog
interpreter should attempt to satisfy.

Example of queries in Prolog:

This query asks whether John likes pizza.

This query asks for all children of Bob.


When a query is posed to the Prolog interpreter, it attempts to find solutions by matching the query
with the predicates and rules defined in the program. If a solution is found, the Prolog interpreter
returns the bindings for the variables in the query that satisfy the predicates. If no solution is found,
Prolog responds with a failure message indicating that the query cannot be satisfied.
In summary, predicates in Prolog represent relationships, properties, or actions, while queries allow
users to interact with Prolog programs by requesting information or solutions to logical problems.
Together, predicates and queries form the basis of logic programming in Prolog, enabling the
representation and manipulation of complex symbolic relationships and knowledge.

Advantages of Prolog:
1. Natural Representation of Problems: Prolog allows problems to be represented
naturally using logical rules and facts, making it well-suited for domains such as
expert systems and natural language processing.

2. Built-in Backtracking: Prolog's backtracking mechanism simplifies the


implementation of search algorithms and problem-solving strategies.

3. Readability: Prolog code tends to be concise and readable, facilitating easy


comprehension and maintenance.

5|Page
Disadvantages of Prolog:
1. Efficiency: Prolog may not be as efficient as imperative languages for certain types of
tasks due to its computational model and backtracking mechanism.

2. Steep Learning Curve: Mastering Prolog requires understanding fundamental


concepts of logic programming, which can be challenging for programmers
accustomed to imperative paradigms.

3. Limited Domain: While Prolog excels in certain domains like symbolic computation
and expert systems, it may not be suitable for performance-critical or highly
procedural tasks.

Applications of Prolog:
1. Expert Systems: Prolog's ability to represent knowledge and perform logical
inference makes it well-suited for building expert systems that emulate human
expertise in specific domains.

2. Natural Language Processing: Prolog has been used in various natural language
processing tasks, including parsing, semantic analysis, and machine translation.

3. Symbolic Computation: Prolog is frequently employed in symbolic computation


tasks such as theorem proving, symbolic integration, and algebraic manipulation.

4. Database Querying: Prolog's pattern matching capabilities make it suitable for


querying and manipulating databases, especially in domains where relational data
models are prevalent.

Prolog Design in Export System:


Designing a Prolog system for an export system involves modeling the various components,
relationships, and rules within the domain of exporting goods. Prolog, with its logic
programming paradigm, is well-suited for such tasks as it allows you to express complex
rules and relationships in a concise and declarative manner. Below is a detailed explanation
of how you might design a Prolog system for an export system:

1. Define Predicates:
Identify the key entities and relationships within the export system and represent them as
predicates. Predicates could include:
 product(Name, Description, Price): Describes a product with its name, description,
and price.

6|Page
 country(Name, Continent): Represents a country and its continent.
 exported_to(Product, Country): Indicates which products are exported to which
countries.
 requires_license(Product, Country): Specifies products that require a license for
export to certain countries.

2. Represent Facts:
Define facts to populate your knowledge base with specific information about products,
countries, and export regulations. For example:

3. Define Rules:
Establish rules that govern the export process, considering factors such as licensing
requirements, pricing, and destination countries. For instance:

 A product requires a license for export to a specific country if it's listed in the
requires_license/2 predicate.

 Pricing rules could be defined based on product specifications or destination


countries.

 Certain products might be restricted or prohibited from export to certain countries due
to legal or regulatory constraints.

4. Implement Query Mechanisms:


Develop query mechanisms to allow users to retrieve relevant information from the system.
Users could query for:

7|Page
 Products exported to a specific country.
 Countries to which a particular product is exported.
 Products requiring licenses for export to a given country.

5. Consider User Interface:


Design a user interface to interact with the Prolog system, allowing users to input queries and
receive meaningful responses. This interface could be a command-line interface, a web
application, or a graphical user interface depending on the intended audience and use case.

6. Testing and Validation:


Thoroughly test the Prolog system with various scenarios to ensure its correctness and
reliability. Validate the results against expected outcomes and refine the system as necessary.

7. Documentation and Maintenance:


Document the design, implementation, and usage of the Prolog system to facilitate its
understanding and maintenance. Provide clear guidelines for future updates, modifications,
and enhancements.
By following these steps, you can design a robust and effective Prolog system for an export
system, enabling efficient management of products, countries, and export regulations.
Prolog's expressive power and logical reasoning capabilities make it a valuable tool for
modeling and solving complex problems in various domains, including international trade
and logistics.

Meta-Programming:

Meta-programming in Prolog refers to the ability to write programs that generate or


manipulate other programs as data. It allows Prolog programs to introspect and modify their
own structure, rules, or behavior at runtime. Meta-programming is a powerful feature that
enables the creation of more flexible, adaptive, and dynamic Prolog systems. Here's a
detailed explanation of meta-programming in Prolog:

1. Dynamic Predicate Manipulation:


Meta-programming in Prolog allows you to create, assert, retract, and modify predicates
dynamically during program execution. This means you can add or remove rules and facts, or
even change the structure of predicates based on certain conditions or inputs.

8|Page
2. Code Generation:
Prolog allows you to generate code programmatically based on specific requirements or
conditions. This can be useful for automatically generating complex queries, rules, or entire
programs based on user input, data analysis, or other runtime factors.

3. Predicate Factoring and Abstraction:


Meta-programming enables you to factor out common patterns or behaviors in your Prolog
code and abstract them into reusable predicates or higher-order predicates. This promotes
code reusability and maintainability by reducing redundancy and improving modularity.

4. Control Structures and Rule Generation:


Meta-programming allows you to dynamically generate control structures such as loops,
conditionals, and recursion within your Prolog programs. You can generate rules and clauses
based on runtime conditions, allowing for more flexible and adaptive program behavior.

5. Debugging and Tracing:


Meta-programming techniques can be used to implement debugging and tracing mechanisms
in Prolog programs. You can dynamically instrument your code to log predicate calls,
backtrack points, variable bindings, and other relevant information for debugging and
analysis purposes.

6. Reflection and Introspection:


Prolog supports reflection and introspection, allowing programs to inspect and manipulate
their own structure and state. Meta-programming techniques enable you to query and analyze
predicates, clauses, variables, and other elements of Prolog programs at runtime.

9|Page
In summary, meta-programming in Prolog provides powerful capabilities for program
generation, manipulation, abstraction, and introspection. It allows Prolog programs to
dynamically adapt and respond to changing requirements or conditions at runtime, enhancing
their flexibility, expressiveness, and utility.

10 | P a g e
EXPERIMENT – 2

Aim: Write simple fact for the statements using PROLOG


a. Ram likes mango.
b. Seema is a girl.
c. Bill likes Cindy.
d. Rose is red.
e. John owns gold.

Steps:

1. Identify Predicate:

2. Define Facts:
Open a text editor, such as Notepad, to write basic facts in PROLOG syntax to
express the provided statements:

3. Save the program directly in the bin folder directory with a .pl or .prolog extension.

11 | P a g e
4. Open GNU PROLOG and compile it by using the consult('exp2prolog.pl').
command.This command will load the contents of the "exp2prolog.pl" file into the
Prolog interpreter, making its predicates and rules available for querying and
execution within the Prolog environment.

5. Enter the queries in the PROLOG interpreter.

12 | P a g e
EXPERIMENT – 3

Aim: Write predicates, one converts centigrade temperatures to Fahrenheit, the other checks
if a temperature is below freezing using PROLOG.

Steps:
1. Create a file (e.g. exp3prolog) with an extension of .pl or .prolog of predicates.

2. Open GNU Prolog and compile it by using the consult() command.

13 | P a g e
EXPERIMENT -4

Aim:- Write a program to implement Breadth First Search Traversal.

Program:

1. Create a text file.

2. Open the prolog console and use the ‘consult’ command to compile the file and use it
as a knowledge base.

14 | P a g e
3. Write the appropriate queries in the console for verification.

Tree Representation:

15 | P a g e
EXPERIMENT – 5

Aim: Write a program to implement Water Jug Problem.

Theory:
The Water Jug Problem is a classic puzzle in which you are given two jugs, a 4-gallon jug
(Jug A) and a 3-gallon jug (Jug B), and your goal is to measure out exactly 2 gallons of water
using these jugs. You can fill the jugs, empty them, or pour water from one jug into the other
until you reach the desired amount.

Source Code:

16 | P a g e
Prolog:

17 | P a g e
EXPERIMENT – 6

Aim: Write a program to remove punctuations from the given string.

Source Code:

1. Create a text file.

2. Open the prolog console and use the ‘consult’ command to compile the file and use it
as a knowledge base.

3. Write the appropriate queries in the console for verification.

18 | P a g e
EXPERIMENT – 7

Aim: Write a program to sort the sentence in alphabetical order.

Source Code:

1. Create a text file.

2. Open the prolog console and use the ‘consult’ command to compile the file and use it
as a knowledge base.

3. Write the appropriate queries in the console for verification.

19 | P a g e
20 | P a g e
EXPERIMENT – 8

Aim: Write a program to implement Hangman game using Python.

Theory:
Hangman is a popular word-guessing game typically played by two or more people. The
game's objective is for one player to guess a hidden word, phrase, or sentence letter by letter
within a limited number of attempts.

Here's how the game usually works:

1. **Setup**: One player (the "host") selects a word or phrase and keeps it hidden from the
other player(s). The word or phrase is represented by a series of dashes, each dash
representing a letter. For example, if the word is "hangman", it might be represented as
"-------".

2. **Guessing**: The other player(s) then take turns guessing letters in an attempt to uncover
the hidden word. The host reveals any correctly guessed letters by replacing the
corresponding dashes with the guessed letter. If the guessed letter is not in the word, the host
marks it as a wrong guess.

3. **Incorrect Guesses**: For each incorrect guess, the host typically draws part of a gallows
with a hanging stick figure (the "hangman"). The drawing is usually incremental, adding one
part for each wrong guess. The game typically ends if the hangman is completed (usually
consisting of a head, body, arms, and legs), indicating that the guesser has run out of
attempts.

4. **Winning and Losing**: The guesser(s) win the game if they successfully guess the word
before the hangman is completed. If the hangman is completed before the word is guessed,
the host wins.

Hangman can be played with various levels of difficulty, such as using longer words or
phrases, limiting the number of incorrect guesses allowed, or using less common letters. It's
often played for fun and as a way to practice vocabulary and spelling skills. Additionally, it
can be adapted into digital versions and educational tools.

21 | P a g e
Source Code:
import random

# List of words to choose from


words = ['apple', 'banana', 'orange', 'grape', 'kiwi', 'pear']

def choose_word(words):
"""Choose a random word from the list."""
return random.choice(words)

def display_word(word, guessed_letters):


"""Display the word with underscores for unguessed letters."""
display = ''
for letter in word:
if letter in guessed_letters:
display += letter + ' '
else:
display += '_ '
return display.strip()

def hangman():
"""Main function to play the Hangman game."""
# Choose a word
word = choose_word(words)
# Initialize variables
guessed_letters = []
attempts = 6

print("Welcome to Hangman!")
print("Try to guess the word.")
print(display_word(word, guessed_letters))

# Main game loop


while True:
guess = input("Enter a letter: ").lower()

if guess in guessed_letters:
print("You already guessed that letter.")
continue
elif len(guess) != 1 or not guess.isalpha():
print("Please enter a single letter.")
continue

guessed_letters.append(guess)

if guess not in word:


attempts -= 1
print("Incorrect guess! Attempts remaining:", attempts)

22 | P a g e
if attempts == 0:
print("You ran out of attempts! The word was:", word)
break
else:
print("Correct guess!")

# Display current state of the word


display = display_word(word, guessed_letters)
print(display)

# Check if the word has been completely guessed


if '_' not in display:
print("Congratulations! You guessed the word:", word)
break

# Play the game


hangman()

Output:

23 | P a g e
EXPERIMENT – 9

Aim: Write a program to implement Hangman game.

Source Code:
1. Create text file.

2. Open the prolog console and use the ‘consult’ command to compile the file and
use it as a knowledge base.

3. Write the appropriate queries in the console for verification.

24 | P a g e
25 | P a g e
EXPERIMENT – 10

Aim: Write a program to implement Tic-Tac-Toe game.

Source Code:
1. Create a text file.

26 | P a g e
2. Open the prolog console and use the ‘consult’ command to compile the file and use it
as a knowledge base.

3. Write the appropriate queries in the console for verification.

27 | P a g e

You might also like