Search code examples
prologcomparesuccessor-arithmetics

Not Equal Operation in swi-prolog


I am trying to compare two peano's number in prolog , but some resualt is wrong .

Anyone can help me , this is my code :

%Not Equal
notequal(0,s(A),X).
notequal(s(A),0,X).
notequal(s(A),s(B),C):- A/=B .

OR

%Not Equal
notequal(0,s(A),X).
notequal(s(A),0,X).
notequal(s(A),s(B),C):- minus(A,s(0),S1),minus(B,s(0),S2),notequal(S1,S2,C) .

The output :

?- notequal(s(0),s(s(0)),S).
false.

?- notequal(s(0),0,S).
true .

?- notequal(0,s(0),S).
true.

First output wrong

Thank you .


Solution

  • You don't need three arguments for such a predicate, after all you want to describe a relation between two numbers. And your last rule should call the predicate itself again:

    notequal(0,s(_)).
    notequal(s(_),0).
    notequal(s(A),s(B)) :-  % s(A) and s(B) are not equal if
       notequal(A,B).       % A and B are not equal
    

    This yields your desired answers:

    ?- notequal(0,0).
    false.
    
    ?- notequal(0,s(0)).
    true.
    
    ?- notequal(s(0),s(0)).
    false.
    
    ?- notequal(s(s(0)),s(0)).
    true ;
    false.
    
    ?- notequal(s(s(0)),0).
    true ;
    false.
    

    You can also use this with only one argument instantiated:

    ?- notequal(s(0),B).
    B = 0 ;
    B = s(s(_G2450)).
    
    ?- notequal(A,s(0)).
    A = 0 ;
    A = s(s(_G2450)).
    

    As you can see all possibilities are covered with these two answers. Even the most general query is producing solutions:

    ?- notequal(A,B).
    A = 0,
    B = s(_G2456) ;
    A = s(_G2456),
    B = 0 ;
    A = s(0),
    B = s(s(_G2460)) ;
    A = s(s(_G2460)),
    B = s(0) ;
    A = s(s(0)),
    B = s(s(s(_G2464))) ;
    .
    .
    .