Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog integer comparison fails with error_type error

Tags:

prolog

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

like image 528
Karim Mtl Avatar asked Dec 24 '22 17:12

Karim Mtl


1 Answers

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))
                       ).
like image 104
coder Avatar answered Jan 21 '23 23:01

coder