[ a, b, c, d] is a list in Prolog. The first item is the head of the list. The remaining part is called the tail.
.(Head, Tail) is the special functor to create lists. For example
.(a, .(b, .(c, .( d, [])))) creates the list above. Let’s observe some operations on lists.
member(X, [X|Tail]).
member(X,[Head|Tail]) :-
member(X, Tail).
defines the membership.
Concatenation:
conc([],L,L).
conc([X|L1],L2,[X|L3] :-
conc(L1,L2,L3).
Adding an item to the head:
add(X,L,[X|L]).
Deleting an item:
del(X,[X|Tail],Tail).
del(X,[Y|Tail],[Y|Tail1]) :-
del(X,Tail,Tail1).
Inserting at any place:
insert(X,List,BiggerList) :-
del(X,BiggerList,List).
Sublist:
sublist(S,L) :-
conc(L1,L2,L),
conc(S,L3,L2).
Permutations:
permutation([],[]).
permutation([X|L],P) :-
permutation(L,L1).
insert(X,L1,P).
Reversing:
reverse([],[]).
reverse([First|Rest],Reversed):-
reverse(Rest,RestReversed),
conc(RestReversed,[First],Reversed).
Palindrome
palindrome(List) :- reverse(List,List).
Length:
length([],0).
length([_|Tail],N):-
length(Tail,N1),
N is 1 + N1.
Sum of the list:
sumlist([],0).
sumlist([H|Tail],Sum):-
sumlist(Tail,Sum1),
Sum is H + Sum1.
