Prolog 家谱查询问题 [英] Prolog Family Tree query issues

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

问题描述

% facts
mother(john, dana).
father(john, david).
mother(chelsea, dana).
father(chelsea, david).
mother(jared, dana).
father(jared, david).
% queries
father(X,Y) :- father(X,Y), write(Y). 
mother(X,Y) :- mother(X,Y), write(Y).
parent(X,Y) :- father(X,Y);mother(X,Y).
sibling(X,Y) :- parent(X,Z), parent(Y,Z), write(Y).

我无法使用这些查询.当我输入父亲命令时,它会正确地告诉我是或否,但不会执行写入命令(与母亲相同).父母"对我来说根本不起作用(因此兄弟姐妹也不起作用).另外,如果我输入兄弟(X,Y).我需要得到所有兄弟姐妹......例如,兄弟姐妹(约翰,切尔西).我需要输出所有可能的兄弟姐妹(也jared).让我知道我哪里出错了,我真的没有看到我的逻辑有问题.谢谢!

I am having trouble getting these queries to work. when I type in the father command, it will tell me yes or no correctly, but won't do the write command (same with mother). "parent" doesn't work at all for me (therefor sibling doesn't either). Also, if I type in sibling(X,Y). I need to get all siblings...for example, sibling(john, chelsea). I need to output all the possible siblings (jared as well). Let me know where I am going wrong, I really don't see an issue with my logic here. Thanks!

推荐答案

基本上,您可以删除不是事实的母亲和父亲谓词.它们是无限循环.由于父级使用它们而兄弟级使用父级,因此所有谓词都是无限循环.

Basically you can remove your mother and father predicates that are not facts. They are infinite loops. Since parent use them and sibling use parent, all your predicates are infinite loops.

要看看会发生什么,你可以这样做:

To see what happens, you can do that :

?- trace, father(john, X).

并观察 prolog 如何处理查询.你很快就会发现比解决父亲,他需要解决父亲,解决父亲,他需要解决父亲,而且永远不会停止......

and observe how prolog handles the query. You'll soon observe than to resolve father, he needs to solve father, and that to solve father, he needs to solve father, and that it never stops...

当两个问题被删除后,我获得了正确的行为:

When the two problematic are removed, I obtain a correct behaviour :

?- father(john, X).
X = david.

?- parent(john, X).
X = david ;
X = dana.

?- sibling(john, X).
john
X = john ;
chelsea
X = chelsea ;
jared
X = jared ;
john
X = john ;
chelsea
X = chelsea ;
jared
X = jared.

现在,为了让你的兄弟姐妹谓词更好,你可以说某人不是它自己的兄弟姐妹,如果你有一个共同的父母就足够了(它将删除重复项):兄弟(X,Y) :- 父亲(Y,Z), 父亲(X, Z), X =\= Y.

Now, to make your sibling predicate better, you could say that someone is not its own sibling and that if you have one common parent it's enough (it will remove the duplicates) : sibling(X,Y) :- father(Y,Z), father(X, Z), X =\= Y.

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

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