Hiren Ai 3
Hiren Ai 3
3
Name: Hiren Daxeshbhai Patel Roll No.: 07
Resources used:
• Windows 10,11
• PC i5 or greater
• Software SWI Prolog
Theory:
• List:
• Lists are an ordered collection of data or items, which can be different types. Lists are
adaptable – they can contain duplicate members, be reordered, added to and edited; as
such, they are described as being mutable.
• A list in Prolog is an ordered collection of items denoted as [i1, i2, …, in].
• Unlike arrays in other programming languages where we can directly access any
element of the array, prolog lists allow direct access of the first element only which is
denoted as Head. Therefore we can write a prolog list as : [Head| Rest], where Rest is
the rest of the list excluding the first element Head.
• Prolog lists allow nonhomogeneous data types of list items.
• Nested lists of arbitrary depths are also allowed in prolog.
• Syntax:
[a | L]
Here L is a list and a is a single element.
• Operators :
• Pipe (|) operator: In prolog, lists have got only one operator, called pipe, denoted by
|. This operator is used to append an element at the beginning of a list.
• Grade• Cut(!) operator: In Prolog, the Cut operator, denoted by ! is a goal that
always succeeds but cannot be backtracked. For example, consider the following
program to find the max element between 2 numbers.
• Operations on list in prolog:
• Find the length of a list:
list_length([], 0).
list_length([_ | L], N) :-
list_length(L, N1),
N is N1 + 1.
% If length of L is N1, then length of [_ | L] will be N1 + 1
• Append a list L2 at the end of another list L1 and put the resultant list in L3.
% Deletion of any element from empty list will produce empty list(base case)
delete_element(_, [], []).
delete_element(X, [X | L], L) :- !.
list_member(X,[X|_]).
list_member(X,[_|TAIL]):-list_member(X,TAIL).
list_length([],0). list_length([_|TAIL],N):-list_length(TAIL,N1),N
is N1+1.
list_concat([],L,L).
list_concat([X1|L1],L2,[X1|L3]):- list_concat(L1,L2,L3).
list_member(X,[X|_]). list_member(X,[_|TAIL]) :-
list_member(X,TAIL). list_append(A,T,T) :-
list_member(A,T),!. list_append(A,T,[A|T]).
list_insert(X,L,R) :- list_delete(X,R,L).
[Y|L1]) :- list_delete(X,L2,L1).
list_perm([],[]).
list_rev([Head|Tail],Reversed) :- list_rev(Tail,
RevTail),list_concat(RevTail, [Head],Reversed).
list_concat([],L,L). list_concat([X1|L1],L2,[X1|L3]) :-
list_concat(L1,L2,L3).
list_order([X]). list_subset([],[]).
list_subset([Head|Tail],[Head|Subset]) :- list_subset(Tail,Subset).
list_subset([Head|Tail],Subset) :- list_subset(Tail,Subset).
list_member(X,[X|_]). list_member(X,[_|TAIL]) :-
list_member(X,TAIL). list_union([X|Y],Z,W) :-
list_member(X,Z),list_union(Y,Z,W). list_union([X|Y],Z,[X|W]) :- \+
list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).list_intersect([X|Y],Z,[X|W]) :-
list_member(X,Z), list_intersect(Y,Z,W).
list_intersect([X|Y],Z,W) :-
Output:
Conclusions: