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.

DOMAINS
person = symbol
people_list = symbol*

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

PREDICATES
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)

CLAUSES
%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]):-
	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, 
	assertz(human(H)),
	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).
	
set_possible_friend(Person):-
	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(Person):-
	set_possible_friend(Person); 
	write_possible_friends(Person).

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

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

 

Tags: , , , ,

Comments

No comments so far.

  • Leave a Reply
     
    Your gravatar
    Your Name