Prolog predicate with variable number of arguments

2020-07-18 03:04发布

问题:

I am writing a Sudoku-Solver with PROLOG. I want the solver to work with all possible sizes of Sudokus, so naturally I need to construct predicates which take a variable number of arguments. (For example to construct the "blocks" in the Sudoku.)

How can I construct or simulate predicates with a variable number of arguments?

回答1:

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).

More often you allocate and modify:

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

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 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.