且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有可变数量参数的 Prolog 谓词

更新时间:2023-11-10 19:17:04

SWI-Prolog - 与其他系统一样 - 提供无限的数量,如果需要,您可以实际使用数组".只需像使用向量一样命名谓词即可.示例分配器:

SWI-Prolog - as some other system - offers unlimited arity, then you can actually work with 'arrays' if you want. Just name a predicate as you would do with a vector. Example allocator:

22 ?- functor(A,a,10).
A = a(_G366, _G367, _G368, _G369, _G370, _G371, _G372, _G373, _G374, _G375).

更频繁地分配和修改:

30 ?- functor(A,a,4),arg(2,A,ciao).
A = a(_G4841, ciao, _G4843, _G4844).

当然,由于许多 Prolog 习语都是基于列表的,您负责任何算法,但请注意,通过 arg/3.我的意思是,它可以搜索参数索引:

Of course, since so many of Prolog idioms are based on lists, you are in charge of any algorithm, but note that nondeterminism (a la member/2) is available by means of arg/3. What I mean, it can search index of argument:

31 ?- arg(A,a(1,2,ciao,4),ciao).
A = 3 ;
false.

edit 由于您要使用库(clpfd),因此更好的构造函数可能是 =../2

edit since you're going to use library(clpfd), a better constructor could be =../2

?- length(L, 9), L ins 1..9, A =.. [a | L].
L = [_G3778, _G3781, _G3784, _G3787, _G3790, _G3793, _G3796, _G3799, _G3802],
A = a(_G3778, _G3781, _G3784, _G3787, _G3790, _G3793, _G3796, _G3799, _G3802),
_G3778 in 1..9,
_G3781 in 1..9,
_G3784 in 1..9,
_G3787 in 1..9,
_G3790 in 1..9,
_G3793 in 1..9,
_G3796 in 1..9,
_G3799 in 1..9,
_G3802 in 1..9.