Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique results from prolog

Tags:

prolog

Is there a easy way to make a query in prolog only return each result once?

for instance I'm trying something like:

deadly(Xn) :- scary(X), Xn is X - 1, Xp is X + 1, not(safe(Xn)), safe(Xp).
deadly(Xp) :- scary(X), Xn is X - 1, Xp is X + 1, not(safe(Xp)), safe(Xn).

deadly(X).

and getting

X = 5

X = 5

X = 5

X = 5

....

Not to usefull for me.

like image 822
BCS Avatar asked Apr 07 '09 06:04

BCS


2 Answers

One thing that you can do is to apply setof/3 to the predicate that generates the solutions. But note that setof/3 is implemented by applying sort/2 to the result delivered by bagof/3 (at least this is the case in SWI-Prolog). So, if your solution generator goes on forever, then setof/3 will never be applied...

So I would say that try to program so that duplicates are not generated, i.e. by using the cut (!) where it makes sense.

like image 90
Kaarel Avatar answered Oct 03 '22 17:10

Kaarel


If I remember correctly there is a predicate solutions (or similar, it's been a while since I programmed Prolog) which collects unique solutions in a list.

Edit: setof/3 is the one I was thinking of. Thanks, Kaarel.

like image 33
starblue Avatar answered Oct 03 '22 17:10

starblue