gpt4 book ai didi

Prolog 初学者 : How to unify with arithmetic comparison operators or how to get a set var to range of values

转载 作者:行者123 更新时间:2023-12-02 03:39:59 28 4
gpt4 key购买 nike

我是 Prolog 新手。我需要编写一个整数加法器,它将 0-9 之间的数字与其他数字 0-9 相加,并产生一个解决方案 0-18。这就是我想做的:

% pseudo code
add(in1, in2, out) :-
in1 < 10,
in2 < 10,
out < 18.

我希望能够这样调用它:

要检查它是否是有效的添加:

?- add(1,2,3).
true.
?- add(1,2,4).
false.

缺少一个变量:

?- add(X,2,3).
X = 1.
?- add(1,4,X).
X = 5.

有多个缺失变量:

?- add(X,Y,Z).
% Some output that would make sense. Some examples could be:
X=1, Y=1, Z=2 ;
X=2, Y=1, Z=3 ......

我意识到这可能是一个非常简单的问题,而且可能非常简单。然而,根据Prolog tutorial我正在使用:

"Unlike unification Arithmetic Comparison Operators operators cannot be used to give values to a variable. The can only be evaluated when every term on each side have been instantiated."

最佳答案

所有现代 Prolog 系统都提供有限域约束,这些约束是可以在所有方向上使用的真实关系(与更底层的算术谓词如 is/2 和 >/2 相比)。在 SWI-Prolog 中:

:- use_module(library(clpfd)).

plus(X, Y, Z) :-
[X,Y] ins 0..9,
X + Y #= Z.

示例结果:

?- plus(1,2,3).
true.

?- plus(1,2,4).
false.

?- plus(X,2,3).
X = 1.

?- plus(1,4,X).
X = 5.

?- plus(X,Y,Z).
X in 0..9,
X+Y#=Z,
Y in 0..9,
Z in 0..18.

由于谓词可以在所有方向上使用,因此将其称为“add/3”不再有意义,因为这意味着一个方向,但谓词真正描述了关系何时成立,因此更通用。

关于Prolog 初学者 : How to unify with arithmetic comparison operators or how to get a set var to range of values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2981222/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com