Prolog - increment by given number

Viewed 48

I have a couple of linked elements with provided cost for traversing them:

link(a, b, 100).
link(b, c, 223).
link(c, d, 311).

I want to find whether the traversal is possible and if it is then return the total cost.

So that the question ?-count(a, d, X). returns X = 634.

Here is my attempt at doing it:

sum(A, B, X) :-
    X is A + B.
count(Start, Finish, Cost) :-
    link(Start, Finish, Cost).
count(Start, Finish, Cost) :-
    link(Start, Through, Tempcost),
    count(Through, Finish, Newcost),
    sum(Cost, Tempcost, Newcost).

The problem is that while I have a general idea how to increment by a fixed number I have a hard time adding up totally different numbers and passing them on to recursion.

My current code returns an "Argument Insuff. Instantiated" error. I know that it often has something to do with the order of the code so I tried to change it around but so far had no luck.

1 Answers

A classic mistake is that you here sum up the Cost with Tempcost to a Newcost. But Newcost is here the cost to get from Through to Finish.

The relation is thus in the opposite way you define it. We can say that the Cost to get from Start to Finish is the same as the cost to take the Start to Through (with a HopCost), plus the RestCost: the cost to get from Through to Finish:

sum(A, B, X) :-
    X is A + B.

count(Start, Finish, Cost) :-
    link(Start, Finish, Cost).
count(Start, Finish, Cost) :-
    link(Start, Through, HopCost),
    count(Through, Finish, RestCost),
    sum(HopCost, RestCost, Cost).
Related