I just finished a wumpus world agent in Prolog so I figured I would put up some little notes about what I learned. Hopefully some other newbies will find it helpful.
In Prolog we can use the knowledge base to hold global variables or flags. To add something to the database we use the following commands:
Therefore the knowledge base can then be queried for isPit or isWumpus as such:
This is true because there is an entry in the knowledge base for isPit. Xp and Xy will be set to the first entry Prolog finds. Note that this is not necessarily in numerical order. Also note that if we want Xp or Xy to be set for use later they MUST be capitalized. The ‘_’ operator could be used for a don’t care value.
To remove the items from the knowledge base we can use the following commands:
retractall will remove all isPit entries and retract will remove specific entries.
Note that dynamic entries to the database that will change during execution must be noted at the top of the code. To do this at the top of the code use the following line:
:- dynamic entryName/x.
where x is the number of parameters.
To express if A then B or C you can say:
(A -> B ; C).
Expressions can be chained together as well such as if A1 and A2 then B or C.
((A1,A2)-> B ; C).
When chaining together knowledge base queries we can use the ‘,’ operator or the ‘->’ operator. If we use the -> operator then this will lock in any choices made before the operator. Therefore if we say:
((location(X,Y)->isSafe(X,Y),isVisited(X,Y))-> do this ; else do this.
We are saying find the first X and Y in the knowledge base which are in a location entry and then check if they are isSafe and isVisited. This can potentially fail if there are two location values and one is safe and visited but the other isn’t. IF the other is grabbed first and locked in by the -> operator then it will not go back and check the safe one. To handle that situation just use commas for everything.
SWI specific commands:
Using SWI prolog there are a few usefull commands. From the terminal we can issue the command “trace.” This will allow us to trace through the next program we enter using the return key to move to the next instruction. To exit trace mode use the command “notrace.”
We can also set spy points on a function by typing “spy(funcName/x).” where x is the number of parameters to that function. Therefore we can run the program to the spy point and if we press “l” it will skip to the next spy point. To remove these use “nospy(funcName/x).”