Logic Programming Using Prolog List Operations
Logic Programming Using Prolog List Operations
Logic Programming Using Prolog List Operations
List Operations
Prolog: Lists
• The Lists are data structures that can be used in different
cases for non-numeric programming.
• Lists are used to store the atoms as a collection.
list_length(L,N)
Fall 2023
list_insert(X, L, R)Logic Programming 5
List: Membership Operation
| ?- list_length([a,b,c,d,e,f,g,h,i,j],Len).
Len = 10
Fall 2023 Logic Programming 7
List: Delete from List
• Suppose we have a list L and an element X, we have to delete
X from L.
| ?- list_delete(a,[a,e,i,o,u],NewList).
NewList = [e,i,o,u] ?
?- list_delete(a,[a,e,i,o,u],NewList).
NewList = [e,i,o,u] ?
| ?- list_delete(a,[a],NewList).
NewList = [] ?
Fall 2023 Logic Programming 10
List: Append into List
• Appending two lists means adding two lists together, or
adding one list as an item. Now if the item is present in the
list, then the append function will not work. So we will create
one predicate namely, list_append(L1, L2, L3).
?- list_concat([1,2],[a,b,c],NewList).
NewList = [1,2,a,b,c]
| ?- list_concat([[1,2,3],[p,q,r]],[a,b,c],NewList).
NewList = [[1,2,3],[p,q,r],a,b,c]
Fall 2023 Logic Programming 19
Repositioning operations of list items
Repositioning
Definition
Operations
list_subset([],[]).
list_subset([Head|Tail],[Head|Subset]) :-
list_subset(Tail,Subset).
list_subset([Head|Tail],Subset) :-
list_subset(Tail,Subset).
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,Z),list_union(Y,Z,W).
list_union([],Z,Z).
| ?- list_union([a,b,c,d,e],[1,2],L3).
L3 = [a,b,c,d,e,1,2]
yes
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) :- \+ list_member(X,Z),
list_intersect(Y,Z,W).
list_intersect([],Z,[]).
Fall 2023 Logic Programming 28
List Intersection Operation
%[mylist_intersect].
| ?- list_intersect([a,b,c,d,e],[a,e,i,o,u],L3).
L3 = [a,e] ?
yes
| ?- list_intersect([a,b,c,d,e],[],L3).
L3 = []
yes