Friday, June 29, 2007

Using Prolog to Find a Friend - 2

Further to my pervious post : Using Prolog to Find a Friend

I have made a minor enhancement to compute the degrees of separation.
/* Prolog Program */
knows(a,b).
knows(b,c).
knows(c,d).
knows(d,e).

exists(X) :- knows(X,_).
exists(X) :- knows(_,X).

friend(X,Y,Deg) :- exists(X), exists(Y), foaf(X,Y,Deg).

foaf(X,Y, Deg) :- knows(X,Y), Deg is 1.
foaf(X,Y, Deg) :- knows(Y,X), Deg is 1.
foaf(X,Y, Deg) :- knows(X,Z),foaf(Z,Y, D1), Deg is D1 + 1.

/* end */

Run it using the goal:
?- friend(a,e,X).
Prolog Answer:
yes.
X / 4
Solution: friend(a,e,4)

Next I will make a List to append the friends name in it.