You need to check whether the head of the List [k, a, k, b, k, [c, d], k, e, k]
contains any list or not. If the head is a list then add k
to the list [c,d]
the resultant list is [k,c,k,d]
. Now add this resultant list to the Main List. My approach is attached below.
is_list1([_|_]).
addK([X],k,[k,X,k]).
addK([H|T],k,[k,H|T1]):- addK(T,k,T1).
addElement([],[]).
addElement([H|T],[H1|Z]):- is_list1(H) , addK(H,k,H1) , addElement(T,Z) .
addElement([H|T],[H|Z]):- \+is_list(H) , addElement(T,Z).
is_list1()
function is used to determine whether a given head is a list or not.
addK()
function adds k
before and after the head to the list given to it.
addElement()
is uses all the above functions to achieve the goal you wanted.
OUTPUT
?- addElement([k, a, k, b, k, [c, d], k, e, k],Z).
Z = [k, a, k, b, k, [k, c, k, d, k], k, e, k]
?- addElement([1,2,[3,4,5],4,5],Z).
Z = [1, 2, [k, 3, k, 4, k, 5, k], 4, 5]
what you have to do is append my code to your existing code, which should look like this.
listpicket(_,[],[k]).
listpicket(K,[H|T],[K,H|L]) :-
listpicket(K,T,L).
is_list1([_|_]).
addK([X],k,[k,X,k]).
addK([H|T],k,[k,H|T1]):- addK(T,k,T1).
addElement([],[]).
addElement([H|T],[H1|Z]):- is_list1(H) , addK(H,k,H1) , addElement(T,Z) .
addElement([H|T],[H|Z]):- \+is_list(H) , addElement(T,Z).
goal(X,FinalList):- listpicket(k,X,L) , addElement(L,FinalList).
OUTPUT
?- goal([1,2,[3,4],5],FinalList).
FinalList = [k, 1, k, 2, k, [k, 3, k, 4, k], k, 5, k]
?- goal([a,b,[c,d],e],FinalList).
FinalList = [k, a, k, b, k, [k, c, k, d, k], k, e, k]
Hope this helped you.
is_list
to check the head to see if it is a list or not. The tail is guaranteed to be a list. – Daniel Lyonslist_si/1
for testing. This ensures that the term is sufficiently instantiated – false