List 提供与预期不同输出的谓词
我有一个称为List 提供与预期不同输出的谓词,list,recursion,prolog,List,Recursion,Prolog,我有一个称为stop\u when_equal的谓词,其工作原理如下: stop_when_equal(L1, L2):- Pred1(L1, L2),L1==L2, ! ; Pred1(L1, L2),stop_when_equal(L2,_). 基本上,它一直将Pred1应用于L1,直到没有任何更改。如果我在这里使用writeln(): stop_when_equal(L1, L2):- Pred1(L1, L2),L1==L2,writeln(L2), ! ;
stop\u when_equal
的谓词,其工作原理如下:
stop_when_equal(L1, L2):-
Pred1(L1, L2),L1==L2, ! ;
Pred1(L1, L2),stop_when_equal(L2,_).
基本上,它一直将Pred1
应用于L1
,直到没有任何更改。如果我在这里使用writeln()
:
stop_when_equal(L1, L2):-
Pred1(L1, L2),L1==L2,writeln(L2), ! ;
Pred1(L1, L2),stop_when_equal(L2,_).
它编写了预期的内容,但输出结果却不同!我知道Pred1工作正常,因为如果我反复应用它,它最终会给我正确的输出,但是我需要一个谓词来为我完成这个任务。我的代码中有什么错误?Phew,我必须确保这是正确的括号
?- write_canonical( ( stop_when_equal(L1, L2):- pred1(L1, L2),L1==L2, ! ; pred1(L1, L2),stop_when_equal(L2,_) ) ).
:-(stop_when_equal(A,B),;(','(pred1(A,B),','(==(A,B),!)),','(pred1(A,B),stop_when_equal(B,_))))
好的
你能解释一下“输出结果不同”吗
尝试:
% https://en.wikipedia.org/wiki/Methods_of_computing_square_roots
pred1(L1,L2) :- L2 is 0.5 * (L1 + 2.0 / L1).
stop_when_equal(L1, L2):-
(pred1(L1, L2),
debug(swe,"L1=~q, L2=~q",[L1,L2]),
L1==L2, !) % what happens if this branch backtracks over pred1(L1,L2)??
;
(debug(swe,"Recursion",[]),
pred1(L1, L2),
stop_when_equal(L2,_)). % Doing nothing with he result?
为我工作
?- debug(swe),stop_when_equal(0.5,L).
% L1=0.5, L2=2.25
% Recursion
% L1=2.25, L2=1.5694444444444444
% Recursion
% L1=1.5694444444444444, L2=1.4218903638151426
% Recursion
% L1=1.4218903638151426, L2=1.4142342859400734
% Recursion
% L1=1.4142342859400734, L2=1.4142135625249321
% Recursion
% L1=1.4142135625249321, L2=1.414213562373095
% Recursion
% L1=1.414213562373095, L2=1.414213562373095
L = 2.25.
似乎有用。在回来检查答案之前,我已经找到了一种方法。无论如何,谢谢你的回答!