序言,测试(X,Y,Z):- Y 是 X + Z

发布于 2024-10-06 06:33:52 字数 209 浏览 0 评论 0原文

当我只知道X时,如何在序言中得到Y和Z?

例如:

test(X, Y, Z) :- X is Y + Z.

但是错误:

?- test(2, Y, Z).
ERROR: is/2: Arguments are not sufficiently instantiated

How to get Y and Z in prolog, when I only know X?

For example:

test(X, Y, Z) :- X is Y + Z.

but error:

?- test(2, Y, Z).
ERROR: is/2: Arguments are not sufficiently instantiated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半寸时光 2024-10-13 06:33:52

这是不可能的,因为您可以选择 Y 为您想要的任何内容,而它们会计算 Z,反之亦然。

尽管如果您知道 YZ 来自某个有限集合(例如小于 5 的正整数),您可以执行以下操作:

valid_number(1).
valid_number(2).
valid_number(3).
valid_number(4).

test(X, Y, Z) :- valid_number(Y), valid_number(Z), X is Y + Z.

It's not possible, because you can choose Y to be anything you want and them compute Z or vice versa.

Although if you know that Y and Z are from some limited set (e.g. positive integers less than 5), you can do something like:

valid_number(1).
valid_number(2).
valid_number(3).
valid_number(4).

test(X, Y, Z) :- valid_number(Y), valid_number(Z), X is Y + Z.
西瑶 2024-10-13 06:33:52

您必须将它们作为参数传递。 Prolog 算术(is/2)不是一根魔杖,它的右参数必须在计算之前完全实例化(无变量)。

如果您希望谓词在多个“方向”上工作,具有基本项和变量的多种组合,您将需要使用约束逻辑编程,但这是逻辑编程的一个相当高级的领域。在有限域上的 CLP 中,你可以说

:- use_module(library(clpfd)).  % this differs between implementations
test(X,Y,Z) :- X #= Y + Z.

You have to pass them as arguments. Prolog arithmetic (is/2) is not a magic wand, its right argument must be fully instantiated (no variables) before it can be evaluated.

If you want the predicate to work in several "directions", with multiple combinations of ground terms and variables, you'll want to use Constraint Logic Programming, but that's a rather advanced area of logic programming. In CLP on finite domains, you can say

:- use_module(library(clpfd)).  % this differs between implementations
test(X,Y,Z) :- X #= Y + Z.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文