combination(X, Y, Z) :-
Z is X + Y.
list_combination(Start, End, List) :-
findall(X+Y=Z, (between(Start, End, X), between(Start, End, Y), combination(X, Y, Z)), List).
这段代码定义了两个谓词。combination(X, Y, Z)
接受两个参数 X
和 Y
,并将它们相加存入 Z
中。list_combination(Start, End, List)
接受三个参数,起始数字 Start
,最大数字 End
和一个返回结果的变量 List
。它使用 findall
来查找列表并将结果存入 List
中。在 findall
的查询中,我们对起始数字和结束数字进行循环,并将所有可能的数字对传递给 combination
谓词来进行相加。
例如,参数 list_combination(1, 3, List)
将返回下面的列表:
[1+1=2, 1+2=3, 1+3=4, 2+1=3, 2+2=4, 2+3=5, 3+1=4, 3+2=5, 3+3=6]
使用 swipl
运行这段代码,然后调用 list_combination(1, 3, List)
,你将得到上述列表。