Search code examples
prologsuccessor-arithmetics

Predicate in prolog which is true if A is smaller or equal to B


I want to write a predicate test(A,B) in prolog which is true if A is smaller or equal to B.

Examples for a query (should return true):

test(s(s(0)), s(s(s(0)))).
test(s(s(s(0))), s(s(s(0)))).

This is the code which I've written so far:

test(0,0).
test(0, s(B)) :- nat(B).
test(s(A),s(B)) :- test(A,B).

but it does not work.


Solution

  • I assume that you use natural numbers as '0 is 0' and 's(A) is A+1'. Then you can write it like this:

    test(0,_).                            % everything is bigger or equal to 0.
    test(s(A),s(B)) :- test(A,B).         % s(A) <= s(B) when A <= B
    

    We are going down with A and B until:
    1) A becomes 0 - that means A <= B, true is returned
    2) B becomes 0 and A not - it means B > A, false is returned.