Using OR operator with different / nonexistent facts in Prolog

I have a fact:

loves(romeo, juliet).

      

then I have a "or" rule:

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

      

As you can see, the dancer doesn't exist, but that shouldn't be a problem, and the juliet should give me back the truth. Instead, it returns me true and then throws an exsitence about the fact of the dancer. Is there a way to write rules for non-existent facts or rules? I need to check if this fact exists?

+3


source to share


3 answers


To achieve "fail if doesn't exist", you can declare a predicate dynamic using a directive dynamic/1

.

For example:

: - dynamic dancer / 1.


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

? - dances (X).
X = juliet.

and no mistakes.

+5


source


As far as I know, there is no way to use a non-exponent predicate. You can either check if a rule exists using the methods described in this question , or you can just have some sort of placeholder to make sure it does exist. The rule doesn't seem very useful if it's always false, so just write a couple of true cases before using it.



dancer(someone). %% To make sure that fact exists 

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

      

+3


source


Technically, you can do something like this:

dances(juliet) :- catch(dancer(juliet), 
                        error(existence_error(procedure, dancer/1), _),
                        false
                  ).

      

Will execute dancer(juliet)

if the predicate exists, fail if not, and fail otherwise.

I would not say that this is a very useful thing.

+1


source







All Articles