How to delete a specified amount of elements in a list without libraries Prolog

Viewed 17

How would I go about deleting a specific amount of elements from a list? My current code doesn't even return a list. I have:

removeSpecific(_, [], [], 0):-!. 

removeSpecific(Element, [Element|Tail], Tail1, NumToDelete):-
      NewNumDelete is NumToDelete-1,
      removeSpecific(Element, Tail, Tail1, NewNumDelete).

removeSpecific(Element, [_|Tail], [_|Tail1], NumToDelete):-
      removeSpecific(Element, Tail, Tail1, NumToDelete). 

When passing something like: removeSpecific(4, [2,4,5,3,4,4], NewList, 2). I get a blank list of the amount of numbers it should have (4) but not the actual amount.

Any help would be appreciated. Thanks.

1 Answers

The reason this happens is because all the underscores _ are nameless variables. Using these twice in the same clause does not result in unifying the two, these are different variables. You can thus give these a name:

removeSpecific(_, [], [], 0).
removeSpecific(Element, [Element|Tail], Tail1, NumToDelete):-
      NewNumDelete is NumToDelete-1,
      removeSpecific(Element, Tail, Tail1, NewNumDelete).
removeSpecific(Element, [Head|Tail], [Head|Tail1], NumToDelete):-
      removeSpecific(Element, Tail, Tail1, NumToDelete).

For the given sample query, this gives us:

?- removeSpecific(4, [2,4,5,3,4,4], NewList, 2).
NewList = [2, 5, 3, 4] ;
NewList = [2, 5, 3, 4] ;
NewList = [2, 4, 5, 3] ;
false.

The first result will delete the first two 4s, the second the first and the last 4s, and the last answer deletes the last two 4s.

Related