Finding Friends of Friends using Prolog

Here is a *really* simple prolog code snippet to find a list of “friends of friends”.
It is a simple program that uses lists, recursion and database usage for dynamic fact storage.

person = symbol
people_list = symbol*

human(person)	%used to store found friend of friend for the goal person

nondeterm has_friend(person, people_list)
nondeterm write_possible_friends(person)
nondeterm is_member(symbol, people_list)
nondeterm check_friends(person, people_list, people_list)
nondeterm find_friends_of_friends(person, person)
nondeterm set_friends_of_friends(person, people_list, people_list)
nondeterm set_possible_friend(person)
nondeterm may_be_friend(person)

%Define relationships
has_friend(serdar, [don, bob, jessica]).
has_friend(don, [sam, serdar]).
has_friend(bob, [serdar]).
has_friend(jessica, [mary, serdar]).
has_friend(sam, [don]).
has_friend(mary, [jessica]).

%Write found possible friends.
write_possible_friends(GoalPerson) :-
	findall(Person, human(Person),L),
	write("Goal Person is: "), write(GoalPerson), nl,
	write("Friends of friends / Possible Friends are: "), write(L), nl,
	retractall(_, dbasedom).

%Check if a person exists in a list
is_member(Person, [Person|_]).
is_member(Person, [_|Tail]):-

%Check recursively a friend of friend is already a friend or the goal person
%If not, add him/her to to DB.
check_friends(Person, [], []).
check_friends(Person, [H|T], Tail) :-
	has_friend(Person, FL),
	not(is_member(H, FL)),
	not(Person = H),
	%write("*** Friend of friend is: "), write(H), nl, 
	check_friends(Person, T, Tail).
check_friends(Person, [H|T],[H|Tail]):-
	check_friends(Person, T, Tail).

%Finds friend list of goal person's friend (Person2)
%and check possible friends of current friend(Person2)
find_friends_of_friends(Person1, Person2):-
	has_friend(Person2, FriendList), 
	check_friends(Person1, FriendList, ProcessedList),

%Traverse every friend of goal person and sets fof
set_friends_of_friends(Person, [], []).
set_friends_of_friends(Person, [H|T], Tail) :-
	%write("Processing friend: "), write(H), nl,
	find_friends_of_friends(Person, H),
	set_friends_of_friends(Person, T, Tail).

set_friends_of_friends(Person, [H|T],[H|Tail]):-
	set_friends_of_friends(Person, T, Tail).
	has_friend(Person, FriendList), 
	set_friends_of_friends(Person, FriendList, ProcessedList).

%Sets possible friends of friends to DB and writes them to the screen.

%may_be_friend(mary).	mary, bob, don, jessica, sam, serdar

P.S: I’m using visual prolog for development.
There is a great document for learning prolog inside DOC folder. (LANGUAGE.doc)


Tags: , , , ,


No comments so far.

  • Leave a Reply
    Your gravatar
    Your Name