英文:
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).
未捕获的异常:错误(实例化错误,(>=)/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 >= 0, Y >= 0, Z >= 0, X =< 3, Y =< 4, Z =< 5.
| ?- konst(S).
uncaught exception: error(instantiation_error,(>=)/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
你的定义仅涉及列表,但未定义值为数字。特别是像=<
这样的算术谓词只能比较具体的数字:1 =< 2
成功,但X =< 2
导致你找到的实例化错误。
要解决你的问题,你可以使用谓词between/3
,如果由前两个参数指定的范围包含第三个参数,则成功:
p([A,B,C]) :-
between(0, 3, A),
between(0, 4, B),
between(0, 5, C).
然后查询:
?- p([A,B,C]), A < 1, B < 1, C < 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 =<
can only compare concrete numbers: 1 =< 2
succeeds but X =< 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 < 1, B < 1, C < 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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论