0

I am trying to find all the brothers of a person.. I have created the following rule..

    find_all_brothers(Z):- findall(X,brother(X,Z),X0),write(X0).

This works however, if a person has more then one brother then it will only find a single brother.. I'm assuming I have to use recursion somehow but I'm a little stuck!

false
  • 10,264
  • 13
  • 101
  • 209
bdavies6086
  • 382
  • 1
  • 5
  • 19

1 Answers1

1

If you have relationships such as:

brother(sam, bill).
brother(bill, fred).

And you want to find all of bill's brothers, you'll need to do a little more:

find_all_brothers(Z) :-
    findall(X, (brother(X, Z) ; brother(Z, X)), X0), write(X0).

To avoid any redundant members of the list, setof will sort and provide only unique members:

find_all_brothers(Z) :-
    setof(X, (brother(X, Z) ; brother(Z, X)), X0), write(X0).
lurker
  • 56,987
  • 9
  • 69
  • 103
  • @false yes, I considered `setof`. I wasn't sure if it was necessary in this case depending upon how the OPs facts and rules were set up. `setof` is certainly safer. – lurker Feb 22 '14 at 17:56
  • Is the order of solutions relevant? Are redundant solutions important? In those cases, `findall/3` would be OK. Otherwise `setof/3` is preferable, **even if** it fails for the case where the `Goal` fails. – false Feb 22 '14 at 17:59
  • Yep, those are good questions whose answers aren't necessarily clear from the original question. – lurker Feb 22 '14 at 18:01