带有可变数量参数的 Prolog 谓词 [英] Prolog predicate with variable number of arguments

查看:59
本文介绍了带有可变数量参数的 Prolog 谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 PROLOG 编写一个数独求解器.我希望求解器能够处理所有可能大小的数独,所以自然地我需要构造带有可变数量参数的谓词.(例如构建数独中的块".)

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?

推荐答案

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.

这篇关于带有可变数量参数的 Prolog 谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆