Search code examples
prologcomparelogicyap

Prolog: comparing predicate value with constant


I have some problems with prolog, specifically I can't compare a value of a predicate with a constant.

predicate(9).
compare(X,Y) :- X<Y.

Running the program:

?-compare(predicate(X),10).

Why doesn't it work? Thank you for your answers.


Solution

  • Like @Boris said before "Predicates don't return values in the way that a function does." Here you must try to instantiate the variables in the head of your rule.
    If you are trying with you predicate compare/2 to find a number X greater than Y, and at the same time this number X should be a fact predicate/1, then add both conditions to the body of your rule or predicate compare/2

    predicate(9).
    compare(X,Y) :- predicate(X), X<Y.
    

    Now if you consult:

    ?- compare(X,10).
    

    The answer will be

    X = 9
    

    As you can see, 9 is smaller than 10, and at the same time 9 is a fact predicate/1. And that is the return value you are looking for.

    Caution

    Note that the operator >/2, requires that both sides are instantiated, so in this case you won't be able ask for the value Y in your predicate

    ?- compare(9, Y)
    </2: Arguments are not sufficiently instantiated
    

    Maybe and if it make sense, you can try to instantiate this variable to a fact predicate/1 too.

    predicate(9).
    predicate(10).
    compare(X,Y) :- predicate(X), predicate(Y), X<Y.
    
    ?- compare(9,Y).
    Y = 10