0% found this document useful (0 votes)
2 views

prolog

The document presents various Prolog programs demonstrating fundamental concepts in logic programming, including arithmetic operations, recursion, list manipulation, and decision-making. Each example illustrates how Prolog's declarative nature differs from imperative languages, showcasing techniques like recursion for factorials and Fibonacci numbers, and list operations such as insertion and removal. These programs serve as foundational exercises for understanding AI applications and the underlying principles of Prolog.

Uploaded by

parmarkrish531
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

prolog

The document presents various Prolog programs demonstrating fundamental concepts in logic programming, including arithmetic operations, recursion, list manipulation, and decision-making. Each example illustrates how Prolog's declarative nature differs from imperative languages, showcasing techniques like recursion for factorials and Fibonacci numbers, and list operations such as insertion and removal. These programs serve as foundational exercises for understanding AI applications and the underlying principles of Prolog.

Uploaded by

parmarkrish531
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

1.

SUM OF TWO NUMBERS


This program defines a simple arithmetic operation using Prolog's
built-in is operator, which evaluates the right-hand side and unifies
the result with the left-hand side. The predicate sum(X, Y, Z)
succeeds when Z is the sum of X and Y. This is a basic example of
how Prolog handles arithmetic expressions declaratively. When you
query sum(5, 7, Result)., Prolog binds Result to 12. This type of
program is foundational for understanding how Prolog differs from
imperative languages — it doesn't execute steps but rather solves
equations based on facts and rules. Arithmetic operations are
fundamental in AI systems for calculating heuristic values, scores, or
transitions in algorithms like A* or Minimax. Though simple, this
example sets the tone for understanding data flow and computation
in logic programming environments.
PROLOG:-
sum(X, Y, Z) :- Z is X + Y.
Query: sum(5, 7, Result).
2. Maximum of Two Numbers
This Prolog program uses rule-based logic to compare two values and
determine the maximum. It uses two clauses: the first clause
maximum(X, Y, X) succeeds when X is greater than or equal to Y, while
the second maximum(X, Y, Y) handles the case where Y is greater. The
order of rules matters — Prolog checks clauses top to bottom. When
queried with maximum(10, 15, Max)., it checks which rule is true and
unifies Max accordingly. This approach reflects decision-making in AI,
such as evaluating scores in games or choosing optimal actions. Prolog
doesn't have if statements like traditional languages; instead, it relies
on pattern matching and logical predicates to select outcomes. The
design of this rule is efficient and can be easily extended to more
complex logic, such as handling a list of numbers to find the maximum
value through recursive comparisons.
PROLOG:-
maximum(X, Y, X) :- X >= Y.
maximum(X, Y, Y) :- Y > X.
Query: maximum(10, 15, Max).
3. Factorial of a Number
The factorial program is a classic example of recursion in Prolog. It
defines a base case: factorial(0, 1), which states that the factorial of 0
is 1. The recursive rule calculates factorial by reducing the problem: for
factorial(N, F), it computes factorial(N-1, F1) and then sets F = N * F1.
This recursive flow continues until the base case is reached. When you
query factorial(5, F)., Prolog recursively evaluates factorial(4),
factorial(3)... down to factorial(0) and then computes the results in
reverse order. This mirrors divide-and-conquer strategies used in AI
for problems like search trees or game states. Understanding
recursion is critical in Prolog since loops aren’t used. This structure
also showcases Prolog's ability to simulate mathematical computation
purely through logical relations, which can be applied to AI algorithms
involving recursive problem solving, such as dynamic programming and
tree traversal.
PROLOG:-
factorial(0, 1).
factorial(N, F) :- N > 0, N1 is N - 1, factorial(N1, F1), F is N * F1.
Query: factorial(5, F).

4. Fibonacci Number
This program computes the Nth Fibonacci number using recursion. Two
base cases are defined: fibonacci(0, 0) and fibonacci(1, 1). For values
greater than 1, it recursively calculates the (N-1)th and (N-2)th
Fibonacci numbers and adds them. When queried like fibonacci(5, F).,
Prolog recursively calculates fibonacci(4) and fibonacci(3) until it
reaches the base cases, then combines the results. Although this
approach is not efficient due to overlapping subproblems (it
recalculates values repeatedly), it effectively demonstrates recursion.
In AI, Fibonacci-like problems can help visualize state transitions and
tree expansion. Prolog’s recursive structure naturally aligns with such
expansions. To optimize it, one could implement memoization or tail
recursion. Still, this naive version is an ideal beginner example for
understanding both the power and limitations of recursion in logic
programming and prepares learners for more complex recursive
structures used in AI tasks.
Prolog:-

fibonacci(0, 0).
fibonacci(1, 1).
fibonacci(N, F) :-
N > 1,
N1 is N - 1,
N2 is N - 2,
fibonacci(N1, F1),
fibonacci(N2, F2),
F is F1 + F2.
Query: fibonacci(6, F).

5. Insert Element at Nth Position in a List


This program demonstrates list manipulation, a crucial skill in Prolog.
The predicate insert_nth(Elem, N, List, Result) inserts an element at the
Nth position in a given list. The base case inserts the element at
position 1 using [Elem|List]. The recursive case reduces N and
reconstructs the list by prepending the head H until the correct
position is found. For example, insert_nth(99, 3, [1,2,3,4], Result). gives
[1,2,99,3,4]. This technique is useful in AI for modifying data structures,
such as inserting nodes in a search tree or updating knowledge bases.
It highlights Prolog's strength in working with recursive lists and
pattern matching. Unlike imperative languages that use index
manipulation, Prolog relies on logical decomposition of the list. This
pattern is frequently reused for various operations on symbolic data,
making it foundational for AI programming in Prolog.
PROLOG:-

insert_nth(Elem, 1, List, [Elem|List]).


insert_nth(Elem, N, [H|T], [H|R]) :-
N > 1, N1 is N - 1, insert_nth(Elem, N1, T, R).
Query: insert_nth(99, 3, [1,2,3,4], Result).

6. Remove Nth Item from a List


This program removes the Nth item from a list using recursion. The
base case remove_nth(1, [_|T], T) drops the head element. The
recursive case traverses the list by decrementing N, preserving
elements until the position is reached. When queried with
remove_nth(2, [a,b,c], R)., Prolog outputs [a,c], removing the second
element. This operation is vital in AI for data pruning, backtracking, or
simulating actions (e.g., removing a move in a game tree). It shows how
to traverse and reconstruct lists, a key skill in logical programming.
Understanding this recursive decomposition prepares students to
implement more advanced structures like priority queues or path
exploration lists. It also reinforces Prolog's declarative nature — you
define what removal means, and Prolog finds how to do it through
matching and backtracking. This program emphasizes precision in rule
definition, as list indexing is handled logically rather than procedurally.
PROLOG:-
remove_nth(1, [_|T], T).
remove_nth(N, [H|T], [H|R]) :-
N > 1, N1 is N - 1, remove_nth(N1, T, R).
Query: remove_nth(2, [a,b,c,d], Result).

7. Remove Every Nth Item from a List


This program extends list manipulation by removing every Nth item
from a list. It uses a helper predicate with a counter (Count) to track
position. At each step, it checks whether the current index modulo N is
0 — if so, it skips the element; otherwise, it includes it in the result.
When queried like remove_every_nth(2, [a,b,c,d,e], 1, R)., Prolog returns
[a,c,e], removing the 2nd and 4th items. This approach simulates filters
or conditional traversals often used in AI, such as skipping nodes or
pruning paths in search algorithms. It introduces logic branching using
conditionals (->) and modular arithmetic within recursive rules. This
program deepens understanding of recursive iteration with state
tracking, which is necessary for AI models that simulate time steps,
action sequences, or periodic updates. It teaches how Prolog can be
used for rule-based stream editing without traditional loop constructs.
PROLOG:-
remove_every_nth(_, [], _, []).
remove_every_nth(N, List, Count, Result) :-
remove_every_nth_helper(N, List, Count, Result).

remove_every_nth_helper(_, [], _, []).


remove_every_nth_helper(N, [H|T], Count, R) :-
( 0 is Count mod N ->
remove_every_nth_helper(N, T, Count+1, R)
; R = [H|R1], remove_every_nth_helper(N, T, Count+1, R1)
).
Query: remove_every_nth(2, [a,b,c,d,e], 1, Result).

8. Append Two Lists


The append_lists/3 predicate joins two lists. The base case states that
appending an empty list to another list results in the second list. The
recursive case moves elements from the first list into the result one by
one, prepending them until the first list is empty. This mimics how
Prolog constructs lists from the head (H) and tail (T). Querying
append_lists([1,2], [3,4], Result). yields [1,2,3,4]. List concatenation is
foundational in symbolic AI — for instance, building paths in graph
traversal, merging knowledge bases, or formatting outputs. Prolog’s
recursive definition provides an intuitive way to understand list
operations without using iterative loops. Since Prolog evaluates the
structure through matching, this reinforces the concept of declarative
programming. Unlike imperative languages where append might be a
built-in operation, Prolog encourages defining such behavior logically,
giving more insight into underlying list-processing mechanisms in AI
tasks.
PROLOG:-
append_lists([], L, L).
append_lists([H|T], L, [H|R]) :- append_lists(T, L, R).
Query: append_lists([1,2], [3,4], Result).
9. Palindrome Check
This program checks if a list is a palindrome by comparing it with its
reverse. It uses the helper predicate reverse_list/2 to reverse the
input list. If the reversed list is equal to the original, the predicate
palindrome(List) succeeds. For example, palindrome([r,a,d,a,r]) is true.
This demonstrates pattern-based logic and recursion for list reversal
— a common AI technique for backtracking, checking symmetries, or
validating constraints. The reverse_list predicate decomposes the list
into head and tail and recursively reconstructs it by appending the
head to the end of the reversed tail. This shows how a simple logical
definition can achieve complex operations. In AI, palindrome checking
could simulate symmetric state validation or pattern recognition.
Moreover, understanding how Prolog reverses data helps in designing
recursive AI algorithms where order matters, such as planning or
sentence generation in natural language processing.
PROLOG:-
palindrome(L) :- reverse_list(L, L).

reverse_list([], []).
reverse_list([H|T], R) :- reverse_list(T, RevT), append(RevT, [H], R).
Query: palindrome([r,a,d,a,r]).

10. Max of Two Numbers


This program checks which of two numbers is greater using simple
conditional rules. Like problem 2, it defines two clauses: max(X, Y, X)
and max(X, Y, Y), depending on which number is greater. When queried
as max(7, 3, M)., it returns M = 7. This operation is essential in
decision-making — for instance, selecting the best move in a game or
comparing heuristic values in search algorithms like A*. Though simple,
this logic encapsulates comparison and branching behavior, which
underlies many AI techniques such as classification, optimization, and
control logic. Prolog’s use of rule-based comparisons instead of if-else
blocks simplifies reasoning. It allows easy chaining or nesting of
decisions, which can later scale to more complex comparisons like
maximum in a list or multi-criteria evaluations. This reinforces how
Prolog handles logic flow naturally and declaratively, a useful skill for
AI tasks involving evaluations or rankings.
PROLOG:-
max(X, Y, X) :- X >= Y.
max(X, Y, Y) :- Y > X.
Query: max(7, 3, M).

You might also like