1

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 ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3816820
  • 37
  • 1
  • 6

3 Answers3

2

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
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166
0
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).
Grzegorz Adam Kowalski
  • 5,243
  • 3
  • 29
  • 40
  • Thank you Adam. But the program you gave throws error. Here is the output: | ?- del1([1,2,3,4],[3,2],R). (0) Call: del1([1,2,3,4],[3,2],_h226) ? (1) Call: see(0) ? (1) Exit: see(0) ? (2) Call: default_error_handler(error(existence_error(procedure,usermod : member / 2),[],[[39947184,39952640,39952512,41346368,40949824,41346496,40028960,41354720,40680192,40679216,40072096,39940656,40628976,39956000,40072096,39940656]])) ? End XSB (cputime 0.02 secs, elapsetime 26.96 secs) – user3816820 Dec 03 '14 at 15:41
  • For del1([1,2,4,5],[2,3],Res), the output should be Res=[1,4,5]. – user3816820 Dec 03 '14 at 15:45
0

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.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61