在递归工作时,我可以跟踪我在另一个变量中获得的价值吗? [英] Can I keep track of value I'm getting in an other variable while working in a recursion?

查看:99
本文介绍了在递归工作时,我可以跟踪我在另一个变量中获得的价值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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).

我想要的成本答案是a和d之间所有C的总和(以上总距离).上面的代码不起作用,它不允许我接受新变量,请有人进行更改.在上面的代码中,这样我就可以得到Cost中的总距离.请记住,我是prolog的新手,谢谢!

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!

推荐答案

您需要使用一个累加器(您的求解谓词中的另一个变量):

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).

在这里介绍累加器并将其初始化为0.

Here you introduce your accumulator and initialize it to 0.

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

如果此步骤是最后一步,则结果是累加器的值(在此处称为TotalCost)加上最后的费用.

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).

如果这不是最后一步,则只需按Cost增加累加器值即可.

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

希望这会有所帮助.

您应该已经为此作业加了标签,因为由于当天早些时候的问题不佳,该问题已经收到很多反对意见.尽管这次您清楚地表明您尝试过,但这是另外一回事.请询问您是否需要其他信息.

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.

这篇关于在递归工作时,我可以跟踪我在另一个变量中获得的价值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆