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.
or, logical disjunction, ; The logical conjunction (logical-and, ∧) of goals is achieved in Prolog by separating the goals by commas: happy(X) :- rich(X), famous(X). says that X is happy if X is rich and X is famous.
A rule in Prolog is a clause, normally with one or more variables in it. Normally, rules have a head, neck and body, as in: eats(Person, Thing) :- likes(Person, Thing), food(Thing). This says that a Person eats a Thing if the Person likes the Thing , and the Thing is food .
A Prolog program consists of a number of clauses. Each clause is either a fact or a rule. After a Prolog program is loaded (or consulted) in a Prolog interpreter, users can submit goals or queries, and the Prolog intepreter will give results (answers) according to the facts and rules.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With