PROLOG - Brothers exercise

44 views
Skip to first unread message

Rafael Santos

unread,
Dec 19, 2016, 3:00:26 PM12/19/16
to SWI-Prolog
womam(a).
womam
(b).
womam
(c).


man
(d).
man
(e).
man
(f).
man
(g).
man
(h).


%son(X,Y) -> X is son of Y
son
(a, d).
son
(a, b).
son
(e, d).
son
(e, b).
son
(c, a).
son
(c, f).
son
(g, a).
son
(g, h).


person
(X):- womam(X).
person
(X):- man(X).


brothers
(X,Y):-
     person
(X),
     person
(Y),
     are_brothers
(X,Y).


brothers
(_,_).


are_brothers
(X,Y):-
     X
\=Y,
     son
(X,Z),
     son
(Y,Z),
     
!.


Thats my code.

When I do:

?- irmaos(X,Y).
X
= a,
Y
= e ;
X
= c,
Y
= g ;
X
= e,
Y
= a ;
X
= g,
Y
= c ;
true.

the results are repeted. It appears twice the "a" is brother of "e", but in different order. How can I solve this?

Barb Knox

unread,
Dec 21, 2016, 3:51:52 AM12/21/16
to SWI-Prolog, Rafael Santos
If g is c's brother then clearly c is also g's brother.

If you want to only show one of these two orderings then also require that X and Y be in alphabetical order: compare(<, X, Y).

But the situation is even worse.  Suppose Huey, Dewey, and Louie all have the same father, so they are all brothers or half brothers.  Then you will get SIX results for them, pairwise in each order, or 3 results if you require alphabetical order.

It looks to me like you need to do some more work on DEFINING THE PROBLEM  before jumping into coding.  For examples, if Bob and Carl have the same mother but different fathers are they to be considered as brothers?  Do you want to distinguish full brothers from half brothers?


-- 
---------------------------
|  BBB                b    \    Barbara at LivingHistory stop co stop uk
|  B  B   aa     rrr  b     |
|  BBB   a  a   r     bbb   |   ,008015L080180,022036,029037
|  B  B  a  a   r     b  b  |   ,047045,L014114L4.
|  BBB    aa a  r     bbb   |
-----------------------------


Reply all
Reply to author
Forward
0 new messages