%% %% Demo by Andy Long, for Mat385 %% %% Please compile this file into SWI-Prolog with the command %% [mat385]. %% %% The period at the end is necessary! %% %% This is an implementation of Example 39, p. 64, of Gersting. %% %% Note that constants are preceded by small letters, whereas variables are %% preceded by capitals. %% %% Once this file is "compiled", then the following commands will %% give you some practice: %% %% ?- eat(bear,fox). %% ?- eat(fox,bear). %% ?- prey(bear). %% ?- prey(fox). %% ?- prey(little-fish). %% %% ?- prey(X). %% will return the first item prolog finds which satisfies prey(X). If %% you type a semi-colon (;), prolog will find the next item satisfying %% prey(X), and so on until it has found all examples. %% %% You can check to see if something is in the database by using the same %% syntax as we use to create our database below: %% %% ?- eat(bear,fish). %% %% will return "Yes", since it is in the database, whereas %% %% ?- eat(bear,grass). %% %% will return "No". %% %% As above, you can type %% ?- eat(bear,X). %% to systematically get a printout of which things a bear eats. %% %% Try these: %% %% ?- in-food-chain(Y,grass) %% ?- in-food-chain(bear,Y) %% %% NOTE: in order to negate a command, use "\+", as in %% \+(eat(fox,rabbit)). %% %% %% NOTE: You can "trace" execution of your command by first issuing the command %% trace. %% %% The following commands create a database of "facts": %% eat(bear,fish). eat(fish,little-fish). eat(little-fish,algae). eat(raccoon,fish). eat(bear,raccoon). eat(bear,fox). eat(fox,rabbit). eat(rabbit,grass). eat(bear,deer). eat(deer,grass). eat(wildcat,deer). eat(fish,bear). animal(bear). animal(fish). animal(little-fish). animal(raccoon). animal(fox). animal(rabbit). animal(deer). animal(wildcat). plant(grass). plant(algae). %% %% Now we'll create some interesting "rules" that we can use: %% %% %% We'll give an example using a logical "or", and a logical "and". %% %% the comma creates a logical "and": prey(P) will only be true if animal(P) %% and there is some Q such that Q eats P. prey(Animal) :- animal(Animal), eat(Preditor,Animal). %% by including two different "standards" for deciding if something is living, %% we create a logical "or". isliving(P) will be true if either animal(P) or %% plant(P) is true: isliving(P) :- animal(P). isliving(P) :- plant(P). %% %% Here's the recursive definition: %% %% We'd start with the base case, in the event that High actually %% eats Low: in-food-chain(High,Low) :- eat(High,Low). %% then we move on to the case in which there is a middle level %% of critters: in-food-chain(High,Low) :- eat(High,Middle), in-food-chain(Middle,Low).