0
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!

Zohaib
  • 363
  • 2
  • 4
  • 15

1 Answers1

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.

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
m09
  • 7,490
  • 3
  • 31
  • 58
  • The code is right i know but i don't know why it is giving 'no solution' always when i take an indirect path like from a to c or e. Also 'is' is not working in turbo prolog and therefore iam using '=', i hope it does'nt make a difference. – Zohaib Nov 27 '11 at 14:33
  • The edit you made made the code wrong. Your line Acc is Acc + Cost makes the clause false because Acc is already bound, that's why you got to declare a new variable (NewTotalCost after my renaming). I reverted your edit and gave better names to the variables. – m09 Nov 27 '11 at 18:05