Experiment 5
Experiment 5
(a) Demonstrate the use of List handling in Prolog which include finding an element, replacing
an element
(b) Write a program to append two givsen list created in Prolog Programming.
1. Open Command Prompt (cmd) and navigate to the folder where the file is saved:
cd C:\Prolog\
gprolog
[list_operations].
Expected Output:
X = [1,2,3,4,5,6].
Explanation
1. Base Case:
find_element(Element, [Element|_]).
o If the head of the list is the element we are looking for, return true.
o _ (underscore) represents the rest of the list, which we don't need to check
anymore.
o Example:
?- find_element(3, [1,2,3,4,5]).
2. Recursive Case:
find_element(Element, [_|Rest]) :-
find_element(Element, Rest).
o If the head is not the element, we ignore it (_) and check the rest (Rest).
o Recursively call find_element/2 on the rest of the list.
o Example:
?- find_element(7, [1,2,3,4,5]).
1. Base Case:
Output: X = [].
Output: X = [1,99,5,99,7].
1. Base Case:
append_lists([], L, L).
Output: X = [4,5,6].
2. Recursive Case:
append_lists([H|T], L, [H|R]) :-
append_lists(T, L, R).
Output: X = [1,2,3,4,5,6].
Final Notes
✔ Recursive Approach:
Test queries:
?- find_element(3, [1,2,3,4,5]).
?- replace_element(2, 99, [1,2,3,4,2], X).
?- append_lists([1,2,3], [4,5,6], X).