在Prolog中使用findall如何在不影响回溯的情况下执行目标内的操作?
下面的示例解释了我正在努力实现的目标:
value('M1', 11, 3).
value('M2', 11, 3).
connection('M1',1, 'A', 'B').
connection('M1',1, 'B', 'C').
connection('M1',2, 'C', 'D').
connection('M1',2, 'D', 'E').
connection('M2',1, 'D', 'F').
run :- bbR('C',[(0,'X',['A'])],_,_).
run2 :- bbR2('C',[(0,['A'])],_,_).
bbR(Destination,[(Cost,_,[Destination|T])|_],Result,Cost):-
reverse([Destination|T],Result).
bbR(Destination,[(Cost,M_1,[H|T])|Rest],Result,CostSol):-
write('----'), nl,
findall( (C, M, [X,H|T]),
( Destination\==H,
connection(M, CX, H, X),
not(member(X,[H|T])),
sumValue(M, M_1, F),
C is CX+Cost+F,
debug_t(H, X, C, F, M)
),
New),
append(New,Rest,All),
sort(All,LS),
bbR(Destination,LS,Result,CostSol).
sumValue(M, M_1, F):-M_1\==M,value(M, 11, F);F is 0.
debug_t(H, X, C, F, M):-
write('<'),write(H),
write('> to <'),write(X),
write('> @ '), write(M),
write('> total='),write(C),
write(' e freq='), write(F),
nl.
bbR2(Destino,[(Cost,[Destino|T])|_],Result,Cost):-
reverse([Destino|T],Result).
bbR2(Destino,[(Cost,[H|T])|Rest],Result,CostSol):-
write('----'), nl,
findall((C,[X,H|T]),
( Destino\==H,
connection(M, CX, H, X),
\+ member(X,[H|T]),
C is CX+Cost,
debug_t(H, X, C, 0, M)
),
New),
append(New,Rest,All),
sort(All,LS),
bbR2(Destino,LS,Result,CostSol).这里的问题是,当我运行“run”时,它会打印:
<A> to <B> @ M1> total=4 e freq=3
<A> to <B> @ M1> total=1 e freq=0而如果我运行“run2”(这是相同的代码,没有调用sumValue和"+ F"),它只打印
<A> to <B> @ M1> total=1 e freq=0从我的调试来看,问题似乎是当findall完成第一个目标并回溯时,sumValue会影响它的行为。
因此,我的主要问题是如何在一定条件下(当"M_1“与”M“不同时)将值(从另一个谓词)求和到变量"C”,而不影响 findall 回溯。
我一整天都在努力想办法解决这个问题,我已经试过用"!“但没有结果。
发布于 2015-01-08 19:44:45
在查询run.和run2.时,您会得到不同的行为,原因是目标sumValue('M1', _, F)被满足了两次:
?- sumValue('M1', _, F).
F = 3 ;
F = 0.我还建议您使用format/2而不是所有write/1谓词。它有助于代码的可读性。
debug_t(H, X, C, F, M):-
format("<~w> to <~w> @ ~w> total=~w e freq=~w~n", [H, X, M, C, F]).https://stackoverflow.com/questions/27848142
复制相似问题