Can I keep track of value I'm getting in an other variable while working in a recursion?

爱⌒轻易说出口 提交于 2019-12-13 21:15:14

问题


predicates
          pathdistance(symbol,symbol,integer).
          solve(symbol,symbol,integer).

clauses
   pathdistance(a,b,10). 
   pathdistance(b,c,20).
   pathdistance(c,d,5).
   pathdistance(d,e,15). 
   pathdistance(a,d,5).
   pathdistance(c,e,10).

solve(X,Z,C):-
     pathdistance(X,Z,C).

solve(X,Z,C):-
     pathdistance(X,Y,Cost),
     solve(Y,Z,C),
     Cost is Cost+C.

goal
    solve(a,d,Cost).

The answer I wanted for the Cost is the sum of all the C's (total distance) between a and d.The above code is not working, it is not allowing me to take a new variable, Can please somebody do the changes in the above code so that i can get the total distance in Cost.Please keep in mind that I am new to prolog,Thanks!


回答1:


You need to use an accumulator (another variable in your solve predicate) :

pathdistance(a,b,10). 
pathdistance(b,c,20).
pathdistance(c,d,5).
pathdistance(d,e,15). 
pathdistance(a,d,5).
pathdistance(c,e,10).

solve(Start, End, Result):-
    solve(Start, End, 0, Result).

Here you introduce your accumulator and initialize it to 0.

solve(Start, End, TotalCost, Result) :-
    pathdistance(Start, End, Cost),
    Result is TotalCost + Cost.

If this step is the final step, your result is the value of your accumulator (named TotalCost here) + the last cost.

solve(Start, End, TotalCost, Result):-
    pathdistance(Start, Waypoint, Cost),
    NewTotalCost is TotalCost + Cost,
    solve(Waypoint, End, NewTotalCost, Result).

If this is not the final step, you just increase your accumulator value by Cost.

Hope this helps.

You should have tagged this homework though since the problem has already received many downvotes due to poor question earlier in the day. Though this time you clearly show that you tried so it's something else. Please ask if you need other informations.



来源:https://stackoverflow.com/questions/8284535/can-i-keep-track-of-value-im-getting-in-an-other-variable-while-working-in-a-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!