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

StackOverflow https://stackoverflow.com/questions/8284535

  •  09-03-2021
  •  | 
  •  

Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top