next up previous contents
Next: Complex structures in Prolog Up: Introduction to logic programming Previous: Facts and rules   Contents

Computing in Prolog

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:

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)?)


next up previous contents
Next: Complex structures in Prolog Up: Introduction to logic programming Previous: Facts and rules   Contents
Madhavan Mukund 2004-04-29