查找 prolog 程序给出错误结果的查询 [英] Finding query for which a prolog program gives incorrect result

查看:34
本文介绍了查找 prolog 程序给出错误结果的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个 Prolog 程序将第三个参数定义为前两个数字参数的最大值:

This Prolog program de fines the third argument to be the maximum value of the fi rst two numeric arguments:

max(X, Y, X) :- X >= Y, !.
max(X, Y, Y).

我认为这个程序运行良好.但我被告知它可能会给出不正确的结果.你能说出时间和原因吗?

I think that this program works just fine. But I am told that it can give incorrect result. Can you tell when and why?

推荐答案

这是教科书的例子.

?- max(5,1,1).
true.

作业:为什么程序出错了?我们如何使程序正确?

Homework: Why is the program wrong? How do we make the program correct?

编辑

max(X, Y, X) :- X >= Y, !.
max(X, Y, Y).

我们的意图是说:

如果 X 大于 Y, Max 为 X.否则,Max 必须为 Y.

If X is greater than Y, then Max is X. Otherwise, Max must be Y.

相反,说的是:

当第一个和第三个参数(X和Max)可以统一,并且X大于Y时,成功.否则,如果第二个和第三个参数(Y和Max)可以统一,则成功.

When the first and third arguments (X and Max) can be unified, and X is greater than Y, succeed. Otherwise, if the second and third arguments (Y and Max) can be unified, succeed.

很明显的问题出现了,那么第一个和第三个参数不能统一,但第二个和第三个可以.

The obvious problem arises then the first and third arguments cannot be unified, but the second and the third can.

改为:

max(X, Y, X) :- X >= Y.
max(X, Y, Y) :- X < Y.

max(X, Y, Max) :- X >= Y, !, Max = X.
max(_, Max, Max).

这篇关于查找 prolog 程序给出错误结果的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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