Suppose you know some facts about pairs of cities and what roads directly connect then. Can you write some logic to give travel directions from city A to city B, even if A and B are not directly connected?
Now you try. Run the code as is, and change the goal to try getting directions between different city pairs.
Type your code here:
See your results here:
The road facts should be pretty clear. You can change these to be for any cities you wish (perhaps more local to you).
The connected clauses are needed because the road from city A to B is also the road from B to A. This clause saves us some work of having to double up on the road clauses to handle this. The R variable stores the road name (like 'Interstate 10'). This clause reads "city X and Y are connected if there's a road between X and Y, or Y and X." ; means "or" in Prolog.
Just use the :- dynamic(road_taken/2). at the moment. More on this later.
The first_time clause is read "it'll be our first time on a road if we haven't driven from city A to B, and we haven't driven from B to A. , means "and" in Prolog. This is important in our routing, as to not have a drive going in circles, using a road more than once. \+ means "not" in Prolog, so \+ road_taken(X,Y) means the road between city X and city Y has not been taken.
update is a short clause we'll use to display directions on the screen. The write command in Prolog will send text to the screen (like print in Lua). nl means write a "newline," or start on the next line.
Ok, route is the key rule to start giving driving directions. Two clauses are needed:
The first route(X,Y) handles directions for cities that are directly connected. It is read "you can route a driver from city X to city Y if X and Y are connected and it's the first time they've been sent down the road that connects X and Y."
The second route(X,Y) handles directions for cities that are not directly connected. How? It introduces a third city Z, that may be used to get from city X to Y. It can be read "you can route a driver from city X to city Y by first finding a city Z that is directly connected to city X. If the road from X to Z has not been taken already, then write out directions to go from X to Z, then try to route the driver from the intermediate city Z to the needed destination Y."
Finally, we run a goal to go from Oaklahoma City to Las Vegas. If you look at the raw road data, you'll see these two cities are not directly connected, so Prolog will have to work its "AI-magic" to find a route.
* There is a little shortcoming in this code that causes the starts to paths aborted by Prolog to be displayed. If you can figure out how to fix it, let us know.
Share your code
Show a friend, family member, or teacher what you've done!