To start off a computation in Prolog, we ask a query. For instance, we may ask, at the Prolog interpreter prompt ?- whether there is a path from 3 to 1, as follows
?- path(3,1).
To answer this, Prolog will try to use the rules given above and see if it can find a satisfying assignment for all the variables that answers this query. In this example, it scans the rules for path(X,Y) from top to bottom and proceeds as follows:
Prolog tries to satisfy the first subgoal by scanning the edge relation from top to bottom and finds edge(3,4), so Z is set to 4.
The second goal then becomes path(4,1). Since (4,1) is not in edge, this again generates two subgoals: Does there exist Z' (a new variable, not the old Z) such that
Once again, to satisfy the first goal we scan edge from the top and find edge(4,5), so Z' is set to 5.
The second goal then becomes path(5,1). Now, (5,1) does belong to edge, so path(5,1) is true.
We can now backtrack and report success--both the subgoals for path(4,1) have succeeded, path(4,1) is true.
Backtracking once more, both the subgoals for the original goal have succeeded, so path(3,1) is true.
Essentially, Prolog does a depth first search through all possible satisfying assignments to the variables in the premises in order to satisfy the goal. In this case, it found a path of length three, even though there is a shorter path of length two. This is because of the way that the facts in edge are arranged. If we had placed the fact edge(3,5) before edge(3,4), Z would have been set to 5 in the first search itself. (What would happen if we place edge(3,2) before both edge(3,4) and edge(3,5)?)