user3816820
user3816820

Reputation: 37

Can anyone help me in writing a prolog program for deleting a list?

Ex: If I have been given two list [1,4,3,2,5,6] and [1,2,3] the final list should be [4,5,6].

i.e., Del([1,4,3,2,5,6], [1,2,3], Result).
----should output Result=[4,5,6].

I have tried something like this:

 delete1(A, [A|B], B).
 delete1(A, [B, C|D], [B|E]) :- delete1(A, [C|D], E).

But the output I'm getting is by deleting the element being passed as an parameter and not a list.

Output:

delete1(a,[a,b,c,d],Res).

   (0) Call: delete1(a,[a,b,c,d],_h210) ?
   (0) Exit: delete1(a,[a,b,c,d],[b,c,d]) ?

Res = [b,c,d]

Can anyone please help me how to go about this ?

Upvotes: 1

Views: 123

Answers (3)

repeat
repeat

Reputation: 18726

Pure and simple: Use tfilter/3 in tandem with list_nonmember_t/3!

Like we did with memberd_t/3, we define list_nonmember_t/3 based on if_/3 and (=)/3:

list_nonmember_t([],_,true).
list_nonmember_t([E|Es],X,T) :-
   if_(E=X, T=false, list_nonmember_t(Es,X,T)).

Let's put it together!

?- tfilter(list_nonmember_t([1,2,3]), [1,4,3,2,5,6], Xs).
Xs = [4,5,6].                         % succeeds deterministically

Upvotes: 2

Eugene Sh.
Eugene Sh.

Reputation: 18331

So your delete1 is a good start, it allows to delete single element from the list, but it is not handling all of the cases. For example the lists that are not containing the element to be deleted. So the right one would be :

delete1(_, [], []).
delete1(A, [A|B], B).
delete1(A, [C|B], [C|E]) :- delete1(A, B, E).

and then using this, you can define your del1 by applying delete1 recursively on the whole list:

del1([], _, []).
del1(L, [], L).
del1(L, [H|T], R) :- 
    delete1(H, L, R1),
    del1(R1, T, R).

And of course you can use builtin list predicates as stated in the other answer.

Upvotes: 0

Grzegorz Adam Kowalski
Grzegorz Adam Kowalski

Reputation: 5565

del1([], _, []).
del1([A|L], B, R) :- member(A, B), del1(L, B, R).
del1([A|L], B, [A|R]) :- not(member(A,B)), del1(L, B, R).

Upvotes: 0

Related Questions