Search code examples
prologrulefact

Using OR operator with different / non existent facts in Prolog


I have a fact:

loves(romeo, juliet).

then i have an 'or' rule:

dances(juliet) :- loves(romeo, juliet).
dances(juliet) :- dancer(juliet).

As you can see dancer fact does not exist but this should be no problem and dances(juliet) should return me true. Instead it returns me true and then throws an exsitence exception about dancer fact. Is there a way to write rules for non existent facts or rules? Do I need to check if the fact exists?


Solution

  • To achieve "failure if not existant", you can declare your predicate dynamic using the directive dynamic/1.

    For example:

    :- dynamic dancer/1.
    

    If you add this directive to your program, you get:

    ?- dances(X).
    X = juliet .
    

    and no errors.