Write a PROLOG program that includes the following operations with lists: member
ID: 3861759 • Letter: W
Question
Write a PROLOG program that includes the following operations with lists: membership testing (is an element member of a list?) first element last element two adjacent elements three adjacent elements append list1 to list2 producing list3 delete element from a list append element to a list insert element in a list compute the length of list reverse a list check whether a list is a palindrome display a list For each of these operations write your implementation of the operation and show an example of its use. If a predicate already exists (predefined in Prolog), modify its name (e.g. myappend or append 1). Lists to be processed can be created by an auxiliary program, defined as facts, or entered from the keyboard.Explanation / Answer
1.to find the first element
domains
list=symbol*
predicates
last(list)
clauses
first([X]):-
write(" Last element is : "),
write(X).
first([Y|Head]):-
last(Head).
2.to find the last element
domains
list=symbol*
predicates
last(list)
clauses
last([X]):-
write(" Last element is : "),
write(X).
last([Y|Tail]):-
last(Tail).
3. to adjecent element
adjacent(X0, X1, [E0,E1|Es]) :-
adjacent_(Es, E0, E1, X0, X1).
adjacent_([], E0, E1, E0, E1).
adjacent_([E2|Es], E0, E1, X0, X1) :-
if_(( E0 = X0, E1 = X1 ),
true,
adjacent_(Es, E1, E2, X0, X1)).
5. append two list
concat([], List, List).
concat([Head|[]], List, [Head|List]).
concat([Head|Tail], List, Concat) :- concat(Tail, List, C), concat(Head, C, Concat).
As suggested by chegg, i have done on 4 sub-part of the question,hope you will find it useful.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.