0
votes

I want to return true, if a fact (A) is declared only once in the Prolog database, return false otherwise. For instance, if we have:

class('Person').
class('Person').
isUniqueClass(A) :- %%% This part I don't know how to do

And I query isUniqueClass('Person'). I want to return false. However, if we have:

class('Person').
isUniqueClass('Person') :- %%% Again same thing goes here

And I query isUniqueClass('Person'). I want it to return true.

2

2 Answers

3
votes

A shorter version of @twinterer answer, using pattern matching:

isUniqueClass(C) :-
 findall(C, class(C), [_]).

edit: refinement

Instead of 'calling' the predicate, metaprogramming should be done using the appropriate builtins, i.e.

isUniqueClass(C) :-
 findall(C, clause(class(C), true), [_]).

In this case it doesn't any difference, because a fact can't have side effects...

1
votes

You can use findall/3 to retrieve a list of all instances, then check the length of the list with length/2. If the list has length 1, then the fact was unique.