1

I'm a beginner in Prolog, and I just want to get the list of all friends of a given person. if i have predicates, like:

friend(hend, khadija).
friend(huda, mariam).
friend(huda, aisha).
friend(huda, lamia).
friend(mariam, hagar).

how can i write a predicate friendList(X,List) that store all friends of given person in List, like:

?- friendList(huda, List).
 List = [mariam, aisha, lamia].

I have tried to write this:

friendList(X,[]):-
   not(friend(X,_)).
friendList(X,L):-
    friend(X,Y),
    friendList(X,T),
    L = [Y|T].

but I get stack limit error. how can i write it correctly, without built-in predicate?

1 Answers1

1
?- friend(huda, F).
   F = mariam
;  F = aisha
;  F = lamia.
?- setof(F, friend(huda, F), Fs).
   Fs = [aisha,lamia,mariam].

Your definition cannot work because of the following :

friendList(X,[]):- false,
   \+ friend(X,_).
friendList(X,L):-
    friend(X,Y),
    friendList(X,T), false,
    L = [Y|T].

?- friendList(huda, List), false.
   loops.

Because this fragment already loops, also your original program loops. You need to change something in the remaining visible part.

false
  • 10,264
  • 13
  • 101
  • 209
  • 1
    it was so usefull, thanks so much. I wana ask how can I implement `setof` predicate by myself? – Mahmoud Sayed Mar 23 '23 at 09:55
  • 1
    Implementing `setof/3` is pretty complex as it has to handle the general case. It is definitely not a beginners' task. – false Mar 23 '23 at 10:06
  • You are right, I have traied to see its implementation and it seems like advanced topic it's just a task in my collage to find list of frind attached to some person really thank you so much for your answer, comments, and your time. – Mahmoud Sayed Mar 23 '23 at 11:25