Search code examples
prologsuccessor-arithmetics

Predicate in prolog which is true if M and N differ more than X


First of all I am completely new to prolog and I am trying to write a predicate length(M,X,N) which is true, if M differs from N more than X.

I wrote the following testcase which is true if M(=dec.5) and N(=dec.2) differ more than X(=dec.2). And it is true in this case because 5 and 2 have a difference of 3 which is more than 2:

?- length(s(s(s(s(s(0))))), s(s(0)), s(s(0))).
   true .

I know that prolog works recursively so I am wondering if I can construct such a predicate with conditions (for example <,>) like in languages like C, or if there is another way to do this in prolog. Sorry for this simple question but I just started with prolog.


Solution

  • You could construct predicates for greater or less. For example:

    greater_than(s(_), 0).
    greater_than(s(X), s(Y)) :-
        greater_than(X, Y).
    

    And similarly:

    less_than(0, s(_)).
    less_than(s(X), s(Y)) :-
        less_than(X, Y).
    

    If you want to find the absolute difference, you could do something like this:

    abs_diff(0, 0, 0).
    abs_diff(s(X), 0, s(X)).
    abs_diff(0, s(X), s(X)).
    abs_diff(s(X), s(Y), D) :-
        abs_diff(X, Y, D).
    

    Those concepts should help kick start some ideas for how to solve the rest of the problem.