Reputation: 33
I have a simple prolog program that is trying to determine who trusts who based of the trusts rule and the knows rule. Here it is
know(joe,jack).
know(joe,sue).
know(joe,betty).
know(sue,betty).
know(jack,betty).
know(bill,betty).
knows(X,Y):- know(X,Y);know(Y,X).
trust(jack,joe).
trust(bill,joe).
trust(betty,jack).
The knows rule is symmetric and transitive,and the trusts rule is defined by
Person X trusts Y if and only if
-X inherently trusts Y, or
-X knows two DIFFERENT people who trust Y.
Trust is not symmetric and not transitive.
I am not sure how to do rules within rules, and the variables seem to be messing me up, as in trying to only have 2 variables as parameters but use 4 in the rule. Any help would be appreciated, thanks.
Upvotes: 1
Views: 1721
Reputation:
Your question somehow suggests that you think you must have in the head of a predicate all variables that appear in the body of a predicate. This is not necessary. Say I wanted to find the number people that someone in our problem definition knows:
?- bagof(X, knows(betty, X), Xs), length(Xs, N).
You maybe really just want to know that Betty knows 4 people, but the toplevel will write the list of people Betty knows anyway. So instead you put it in a predicate:
knows_count(X, N) :-
bagof(Y, knows(X, Y), Ys),
length(Ys, N).
So now you only see what you need to see:
?- knows_count(betty, N).
N = 4.
?- knows_count(X, N).
X = betty, N = 4 ;
X = bill, N = 1 ;
X = jack, N = 2 ;
X = joe, N = 3 ;
X = sue, N = 2.
You have now "hidden" the list of people in the body of knows_count/2
.
To define the second case of trusts/2
, you can do the same:
trusts(X, Y) :-
knows(X, A), trust(A, Y), ... % and so on
As pointed out by @mat, now all you have to do is make sure that all the people whom "X knows" in the body of the predicate are not the same person. See the link in the comment by @mat or just search Stackoverflow for [prolog] dif
.
Upvotes: 3