I am trying to resolve exercise 2 of lists construction section of this page:
Write a program to delete all reference of a particular item from a list. It should have three arguments. The list you wish to use, the item to delete, and the resulting list.
Here is the script I came up with:
delete_all([],Y,[]).
delete_all([X|T],Y,[X|Result]):-
X =\= Y, /* is X different than Y */
delete_all(T,Y,Result). /* if so then go find the rest */
delete_all([ThrowAway|Tail],Y,Result):- /* disgard the head */
delete_all(Tail,Y,Result). /* and look in the tail */
And here are the corrects results that it should give:delete_all([a,b,a,c,a,d],b,Result).
% delete_all([a,b,a,c,a,d],a,Result).
% Result = [b,c,d]
% delete_all([a,b,a,c,a,d],b,Result).
% Result = [a,a,c,a,d]
% delete_all([a,b,a,c,a,d],prolog,Result).
% Result = [a,b,a,c,a,d]
Instead I am getting this error:
| ?- delete_all([a,b,a,c,a,d],a,Result).
uncaught exception: error(type_error(evaluable,a/0),(=\=)/2)
I am using gprolog under ubuntu 16.04.
Thank you
A more efficient answer using if_/3
from module reif
:
delete([],_,[]).
delete([H|T],X,L):- if_(
H = X,
delete(T,X,L),
(L = [H|L1], delete(T,X,L1))
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With