Prolog,找到朋友的朋友 [英] Prolog, find friend of friend

查看:51
本文介绍了Prolog,找到朋友的朋友的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Prolog 的新手.我正在尝试编写一个查询来检查一个人是否是另一个人的朋友或朋友的朋友.

I'm new to Prolog. I'm trying to write a query to check if a person is the friend or friend of friend of another person.

我有一些这样的事实:

friends(joe, [john, ann, pete, ellen, 
          maria, jose, bruno, ali, jing, yang]).
friends(john, [rick]).
friends(ellen, [mia, xing, jun, maria]).
friends(maria, [pete, ellen, zhang, jose, serena]).
friends(serena, [ali, rick, zhang, mia]).
friends(jose, [maria, jose, bruno, ali, jing]).

我的目标是编写这样的查询:

My target is to write a query like this:

visible(joe, ann).
true

我做了这样的事情:

visible(X,Y) :- friends(X,[Y|T]); member(Y,T).
visible(X,Y) :- visible(X,Z), visible(Z,Y).

member(X,[X|T]). 
member(X,[H|T]) :- member(X,T).

但它变成了一个无限循环.我不知道如何编写基本案例.

But it becomes an infinite loop. I don't know how to write the base case.

关系是一个带有循环的图.有没有办法递归地找到朋友的朋友,传​​递性?

The relationship is a graph with loop. Is there anyway to recursively find the friend of friend, transitively?

推荐答案

visible(X,Y):- friends(X,YS), member(Y,YS).
visible(X,Y):- friends(X,XF), friends(Y,YF), member(Z,XF), member(Z,YF).

第一行检查两个人是否是直接的朋友(YX 的朋友列表中).第二行检查两个 peolpe 是否是朋友的朋友(元素 Z 都在 XY 的朋友列表中.如果你还想知道您可以添加 write(Z) 的共同朋友是什么).例如,在这种情况下,joejohn 的朋友,但反之亦然.如果你也想要这个属性,你应该添加

The first line checks if two people are directly friends (Y is in the list of friends of X). The second line checks if two peolpe are friend of friends (an element Z is both in the list of friends of X and Y. If you also want to know wich is the friend in common you could add write(Z)). In this case, for instance, joe is friend of john but no viceversa. If you want also this property you should add

visible(X,Y):- friends(Y,XS), member(X,XS).

查询:

?-visible(john,serena).
true.

?-visible(joe,john).
true.

?-visible(john,joe).
true. (only if you add the third line of code).

这篇关于Prolog,找到朋友的朋友的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆