0
votes

I currently have this code that inserts an element into a list:

listpicket(_,[],[k]).
listpicket(K,[H|T],[K,H|L]) :-
    listpicket(K,T,L).

It currently produces this result:

L = [k, a, k, b, k, [c, d], k, e, k]

However, I am trying to get the program to insert a k into [c,d] such as shown:

L = [k, a, k, b, k, [k, c, k, d, k], k, e, k]

I have a feeling I'm supposed to use is_list to check if the tail is a proper list or not, and then create another recursion inside to insert the k element just like the outside. However, I'm quite new to Prolog and I'm trying to understand how I can introduce a conditional inside the listpicket method.

1
What you actually need to do is use is_list to check the head to see if it is a list or not. The tail is guaranteed to be a list.Daniel Lyons
Rather use list_si/1 for testing. This ensures that the term is sufficiently instantiatedfalse

1 Answers

0
votes

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.