1
votes

when I use prolog's built-in predicate "subtract/3" : subtract(+Set, +Delete, -Result) in for example:

subtract([a,b,c,d,c,c,d,e], [c,a], X).  
X = [b, d, d, e].  

but I want to subtract each item in +Delete from +Set ONCE. I mean, I want

subtract([a,b,c,d,c,c,d,e], [c,a], X). to give
X = [b, d, c, c, d, e].

How can I do this?

2

2 Answers

2
votes

You can build your own procedure that does that. For example:

subtract_once(List, [], List).
subtract_once(List, [Item|Delete], Result):-
  (select(Item, List, NList)->
    subtract_once(NList, Delete, Result);
    (List\=[],subtract_once(List, Delete, Result))).

In every iteration you take one item from the list of items to remove, and extract one element from the input list, and then continue using the remainder of both lists.

2
votes

You can do something along these lines :

subtract_custom(Remainder, [], Remainder).
subtract_custom(List, [Current|Delete], X) :-
    select(Current, List, Rest),
    subtract_custom(Rest, Delete, X).

It's if you want it to fail when a deletion fails. Else you got to adapt it a little.