Adrian
Adrian

Reputation: 20058

prolog code explanation

Hello could someone help me udnerstand how this code works ?

go(Start,Dest,Route):-
    go0(Start,Dest,[],R),
    rev(R,Route).

go0(X,X,[X|T]).
go0(Place,Y,T,R):-
    legalNode(Place,T,Next).
    go0(Next,Y,[Place|T],R)

legalNode(X,Trail,Y):-
    (a(X,Y);a(Y,X)),
    legal(Y,Trail).

Upvotes: 0

Views: 326

Answers (1)

Bart
Bart

Reputation: 20030

I'm assuming this is taken from the "Programming in Prolog" book? It is actually pretty well explained in there.

What the code does is given a start location and a destination give you a route if it exists. This will be put in Route.

rev, as defined in the book, reverses a results stored in R and places it in Route, basically because the result is backwards.

The remainder of the code looks for a possible route from Start to Dest by checking if there is a direct link (that's what the a(X,Y) define) between two locations or if you can get there via one of the locations there is a direct link with.

With that and the book in hand, you should be able to figure out the code.

Upvotes: 2

Related Questions