Mahmoud Sayed
Mahmoud Sayed

Reputation: 11

How to get the list of all friends of a given person in prolog?

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?

Upvotes: 1

Views: 297

Answers (1)

false
false

Reputation: 10102

?- 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.

Upvotes: 1

Related Questions