Reputation: 109
I am new to prolog and want to make a rule statement for whether 2 people are cousins.
This is my current code, I added "or" to where I need the or
operator:
cousins(E, F) :- siblings(A, C) or siblings(A, D) or siblings(B, C) or siblings (B, D), parent(A, E), parent(B, E), parent(C, F), parent(D, F).
I need just one of the siblings()
to pass, but all parent()
must pass.
Upvotes: 6
Views: 7804
Reputation: 71065
In Prolog, an "or" operator is ;
. Or it can be achieved by having different clauses for the predicate.
Let's see what happens if your first alternative turns out to hold:
cousins( E, F):-
siblings(A, C),
parent( A, E),
parent( B, E),
parent( C, F),
parent( D, F).
Or, what happens if the 2nd holds?
cousins( E, F) :-
siblings(A, D),
parent( A, E),
parent( B, E),
parent( C, F),
parent( D, F).
Similar for 3rd and 4th:
cousins(E, F) :- siblings(B, C),
parent(A, E), parent(B, E), parent(C, F), parent(D, F).
cousins(E, F) :- siblings (B, D),
parent(A, E), parent(B, E), parent(C, F), parent(D, F).
Now you have your "or" condition expressed by the four clauses.
But you must have left many important details out. You probably wanted to have two pairs of parents, so you need to add the inequalities: parent(A, E), parent(B, E), A \= B
etc. But then, the new 2nd clause is just a copy of the 1st, up to some variables renaming; same for the 3rd and 4th clauses. It'll suffice to leave just one of each pair.
But why would you need to know the both parents of a person? You don't, really. What does it matter, if it's a mother or a father? It doesn't. So, in the end, just one clause will be sufficient:
cousins( E, F):-
siblings(A, C),
parent (A, E),
parent( C, F).
You still have to check for some degenerate cases, so you won't ever end up proclaiming a person their own cousin.
Upvotes: 7