Peter Rosqvist
Peter Rosqvist

Reputation: 1

How to increment a variable during a recursion in Prolog?

I am trying to write a program that finds out how many stops there are in a flight from the origin to the destination.

flight(dgz, qyy).
flight(dgz, azi).
flight(qyy, csi).
flight(azi, tva).
flight(csi, ppg).
flight(tva, brw).
flight(brw, csi).


route(Orig, Dest, Stops) :- Stops is 0, flight(Orig, Dest).
route(Orig, Dest, Stops) :- Stops is Stops+1, flight(Orig, Layover), route(Layover, Dest).

I get the error, "Arguments are not sufficiently instantiated". I don't understand why. I declared that Stops is 0 in the first rule. Do you have any insight? Thanks!

Upvotes: 0

Views: 294

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 28983

I declared that Stops is 0 in the first rule.

A person stands in a carpark looking for their car. It's not there. "I don't understand why", they say, "I parked it in a different carpark earlier".

In C, x = x + 1 is assignment. In Prolog it is a statement that is not true, 0 is not 0 + 1.

route(Orig, Dest, Stops) :- 
    Stops is 0,
    flight(Orig, Dest).

route(Orig, Dest, Stops) :- 
    Stops is Stops+1,
    flight(Orig, Layover),
    route(Layover, Dest).  % <-- what's missing here?
                           %     there is no route() with
                           %     only two parameters.

That missing argument to route is where you would get Stops as 0 from the first rule, here you would get the value of 0 out, add 1 to that to get Stops for this rule (not calling them all the same thing).

Upvotes: 1

Related Questions