Prolog 打印所有可能的列表

huangapple go评论60阅读模式
英文:

Prolog print all possible Lists

问题

以下是您提供的文本的翻译部分:

"我正在尝试打印出给定变量的每个可能的列表。使用本机函数时,这可以正常工作,但一旦我用列表来做这个,Prolog就会抛出异常。

这是我的代码(简化版):

first(A, L) :- L = [K|_], A = K.                % L的第一个元素是A
second(A, L) :- L = [_|R], R=[F|_], A = F.      % L的第二个元素是A
third(A, L) :- L = [_|R], second(A, R).         % L的第三个元素是A

konst(S) :- first(X, S), second(Y,S), third(Z,S), X >= 0, Y >= 0, Z >= 0, X =< 3, Y =< 4, Z =< 5.

| ?- konst(S).
未捕获的异常:错误(实例化错误,(&gt;=)/2

基本上,它应该打印出在[0,0,0]和[3,4,5]之间的每个单独的列表。

我在这里漏掉了什么吗?"

英文:

I am trying to print out every possible list for a given variable. With native functions, this is working fine, but as soon as I do this with lists, prolog throws an exception.

This is my code (simplified):

first(A, L) :- L = [K|_], A = K.                % First element of L is A
second(A, L) :- L = [_|R], R=[F|_], A = F.      % Second element of L is A
third(A, L) :- L = [_|R], second(A, R).         % Third element of L is A

konst(S) :- first(X, S), second(Y,S), third(Z,S), X &gt;= 0, Y &gt;= 0, Z &gt;= 0, X =&lt; 3, Y =&lt; 4, Z =&lt; 5.

| ?- konst(S).
uncaught exception: error(instantiation_error,(&gt;=)/2)

So basically it should print out every single list between [0,0,0] and [3,4,5].

Am I missing something here?

答案1

得分: 0

你的定义仅涉及列表,但未定义值为数字。特别是像=&lt;这样的算术谓词只能比较具体的数字:1 =&lt; 2 成功,但X =&lt; 2 导致你找到的实例化错误。

要解决你的问题,你可以使用谓词between/3,如果由前两个参数指定的范围包含第三个参数,则成功:

p([A,B,C]) :-
  between(0, 3, A),
  between(0, 4, B),
  between(0, 5, C).

然后查询:

?- p([A,B,C]), A &lt; 1, B &lt; 1, C &lt; 1.
A = B, B = C, C = 0 ;
false.

按预期工作。这是由于Prolog内置算术的限制。如果你想超越这一点,关键词是(有限)约束逻辑编程(CLP)。其中一个Prolog库是clp(Z)

英文:

Your definition just speaks about lists but does not define that the values are numbers. In particular, the arithmetic predicates like =&lt; can only compare concrete numbers: 1 =&lt; 2 succeeds but X =&lt; 2 leads to the instantiation error you found.

To solve your problem you can use the predicate between/3 that succeeds if the range given by the first two arguments covers the third:

p([A,B,C]) :-
  between(0, 3, A),
  between(0, 4, B),
  between(0, 5, C).

Then the query

?- p([A,B,C]), A &lt; 1, B &lt; 1, C &lt; 1.
A = B, B = C, C = 0 ;
false.

works as expected. This is due to the limitations of Prolog's built-in arithmetic. If you want to go beyond that the keyword is (finite) constraint logic programming (CLP). One of the Prolog libraries for that is clp(Z).

huangapple
  • 本文由 发表于 2023年3月3日 18:26:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定