问题描述
线索
四位客人(Mustard 上校、Plum 教授、Scarlett 小姐、Green 女士)参加了在 Boddy 先生家中举办的晚宴.突然,灯灭了!当他们回来时,博迪先生死在桌子中央.每个人都是嫌疑人.经过进一步检查,发现以下事实:
Four guests (Colonel Mustard, Professor Plum, Miss Scarlett, Ms. Green) attend a dinner party at the home of Mr. Boddy. Suddenly, the lights go out! When they come back, Mr Boddy lies dead in the middle of the table. Everyone is a suspect. Upon further examination, the following facts come to light:
- 博迪先生与格林女士有染.
- Plum 教授与 Green 女士结婚.
- 先生博迪非常富有.
- Mustard 上校非常贪婪.
- 思嘉小姐也与博迪先生有染.
谋杀有两种可能的动机:
There are two possible motives for the murder:
- 仇恨:如果某人与他/她的配偶有婚外情,则某人会恨另一个人.
- 贪婪:如果某人贪婪而不富有,而受害者很富有,则他们愿意杀人.
A 部分:在您的 Prolog 程序中写入上述事实和规则.为这些人使用以下名称:colMustard、profPlum、missScarlet、msGreen、mrBoddy.小心你如何编码(或不编码)像婚姻这样的对称关系 - 你不想要无限循环!已婚(X,Y) :-已婚(Y,X) % 无限循环
Part A: Write the above facts and rules in your Prolog program. Use the following names for the people: colMustard, profPlum, missScarlet, msGreen, mrBoddy. Be careful about how you encode (or don’t encode) symmetric relationships like marriage - you don’t want infinite loops! married(X,Y) :- married(Y,X) % INFINITE LOOP
?-suspect(Killer,mrBoddy)
Killer = suspect_name_1
Killer = suspect_name_2
etc.
B 部分:写一个谓词,嫌疑人/2,确定嫌疑人可能是谁,即谁有动机.
Part B: Write a predicate, suspect/2, that determines who the suspects may be, i.e. who had a motive.
?-suspect(Killer,mrBoddy)
Killer = unique_suspect.
C 部分:将单个事实添加到您的数据库中,这将导致存在唯一的嫌疑人.在源注释中清楚地指出这一行,以便可以删除/添加它评分.
Part C: Add a single factto your database that will result in there being a unique suspect.Clearly indicate this line in your source comments so that it can be removed/added forgrading.
?-suspect(Killer,mrBoddy)
Killer = unique_suspect.
每当我输入
Whenever I type in
suspect(Killer,mrBoddy).
我明白了
suspect(Killer,mrBoddy).
Killer = profPlum
我不见了
Killer = colMustard.
这是我的来源.
%8) Clue
%facts
affair(mrBoddy,msGreen).
affair(missScarlett, mrBoddy).
affair(X,Y) :- affair(X,Y), affair(Y,X).
married(profPlum, msGreen).
married(X,Y) :- married(X,Y), married(Y,X).
rich(mrBoddy).
greedy(colMustard).
%rules
hate(X,Y) :- married(X,Spouse), affair(Y,Spouse).
greed(X,Y) :- greedy(X), not(rich(X)), rich(Y).
%suspect
suspect(X,Y):- hate(X,Y).
suspect(X,Y):- greed(X,Y).
推荐答案
问题在于谓词affair/2
和Married/2
的递归规则.尝试使用它们很容易导致无限循环(即直到堆栈内存耗尽).您必须在每种情况下使用不同的谓词来表示如果 X 与 Y 有染,则 Y 与 X 有染.您还需要更改 suspect/2
谓词的定义调用这些新谓词.
The problem is the recursive rules of the predicates affair/2
and married/2
. Attempting to use them easily leads to an endless loop (i.e. until the stack memory is exhausted). You must use a different predicate in each case to represent that if X is having an affair with Y, then Y is having an affair with X. You also need to change your definition of the suspect/2
predicate to call those new predicates.
为了更好地理解为什么会出现无限循环,请使用 Prolog 系统的跟踪工具.试试:
To better understand why you get an endless loop, use the trace facilities of your Prolog system. Try:
?- trace, suspect(Killer, mrBoddy).
然后一步一步来.
这篇关于Prolog - 规则是正确的,但没有按照预期的方式输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!