我有一个谓词叫 stop_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的工作是正确的,因为如果我一遍又一遍地应用它,它最终会给我正确的输出,但我需要一个谓词来为我完成这个任务。我的代码中的错误是什么?
唷,我得确保这个是正确的括号。
?- 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.
似乎是工作。