Prolog- Returning elements from facts

637 views Asked by At

i encounter a problem with facts. Let's say i got 3 facts and check(X) question.

fact(a,b).
fact(b,c).
fact(a,d).

check(X):-
//some calculation with fact()

How to make above question to return list of elements for given X from all facts? For instance: check(a) would give result b and d. So i can use this const later. check(b) would return c. I would be grateful for help!

1

There are 1 answers

0
false On BEST ANSWER

You need an extra argument for the list. So you cannot call it check/1 having a single argument, but — let's say — related_to/2.

related_to(X, Ys) :-
   setof(Y, fact(X, Y), Ys).

Sample queries:

?- related_to(a, Xs).
   Xs = [b, d].
?- related_to(b, Xs).
   Xs = [c].
?- related_to(d, Xs).
   false.
?- related_to(X, Xs).
   X = a, Xs = [b,d]
;  X = b, Xs = [c].

Note that the relation will fail for inexistent nodes like d above. On the other hand, you can even ask the most general goal getting all possible answers at once.

Also note that this relation is not monotone: If you add further facts, previously obtained results no longer hold. Like by adding fact(a,f) the goal related_to(a, [b,d]) no longer holds. Instead related_to(a,[b,d,f]) now holds.