

path ( X, Y ) :- edge ( X, Z ), path ( Z, Y ). The following: path ( X, Y ) :- edge ( X, Y ). Or finding an edge between X and Z and a path between Z and Y, something like Now the path method can be defined as finding an edge between X and Y directly Really need to fix this by naming these two things differently, like so: edge ( a, b ). Of the problem is that we don’t have a predicate for validating a path with aĭifferent name from the fact that represents the edge between two nodes. Still be able to calculate all of the reachable nodes for a given node. To have to find a way to change our solution so that we don’t stack overflow and We’d really like the answer to be and for that we’re going Query Prolog for all of the nodes we can reach from a, like so: This now works as desired but presents a small problem which is that we can’t path ( X, Y ) :- atom ( X ), atom ( Y ), path ( X, Z ), path ( Z, Y ). Which would look like so: path ( a, b ). That we simply validate that both X and Y are valid atoms and not variables. Is to make sure that when we start on a path to look for Z that connects X and Y

Of path facts until it runs out of stack space. Keeps instantiating variables for Z that it can then match on a longer sequence This is because we don’t have a termination rule and Prolog Oh shoot, seems when we ask for a path that can’t be solved that we run out of With that predicate we can now ask Prolog a few different questions:įatal Error: local stack overflow (size: 8192 Kb, environment variable used: LOCALSZ) Very similar to the sentence we just wrote: path ( X, Y ) :- path ( X, Z ), path ( Z, Y ).

For example if X is connected to Z and Z isĬonnected to Y then there is a path between X and Y, which is Prolog is Now all we need is to define a simple predicate that can calculate paths byĬomposition of existing paths. We could represent the above using the following facts in Prolog: path ( a, b ). So lets say we wanted to represent the following graph: % a - b - e % \ / % \ / % c - d - f % \ % \ % g Traversal methods that do things that in other languages would take hundreds Languages and now we’re going to show you a data structure that can be veryĮasily represented in Prolog and for which you can very easily define There are a few things we’ve shown that Prolog can do better than other
