Prolog – Food Web Challenge

Prolog is a language built around the Logical Paradigm: a declarative approach to problem-solving.

There are only three basic constructs in Prolog: facts, rules, and queries.

A collection of facts and rules is called a knowledge base (or a database) and Prolog programming is all about writing knowledge bases. That is, Prolog programs simply are knowledge bases, collections of facts and rules which describe some collection of relationships that we find interesting.

So how do we use a Prolog program? By posing queries. That is, by asking questions about the information stored in the knowledge base. The computer will automatically find the answer (either True or False) to our queries.

Source: http://www.learnprolognow.org/

Knowledge Base (Facts & Rules)


Check the following knowledge base used to store the information that appears on a food web:

/* Facts */
plant(grass).
plant(berries).
plant(nuts).

insect(caterpillar).
insect(butterfly).

animal(squirrel).
animal(goldfinch).
animal(fox).
animal(snake).
animal(frog).
animal(eagle).
animal(X) :- insect(X).

insectivore(frog).
insectivore(goldfinch).  

eats(caterpillar,grass).
eats(butterfly,berries).
eats(goldfinch,berries).
eats(squirrel,nuts).
eats(fox,squirrel).
eats(fox,goldfinch).
eats(snake,goldfinch).
eats(snake,frog).
eats(eagle,frog).
eats(eagle,snake).
eats(eagle,goldfinch).
eats(X,Y) :- insectivore(X), insect(Y).         

/* Rules */
herbivore(X):- eats(X,Y), plant(Y).
carnivore(X):- eats(X,Y), animal(Y).
omnivore(X):- herbivore(X), carnivore(X).

predator(X,Y):- eats(X,Y).
prey(X,Y):- eats(Y,X).

pyramid(X,Y):- prey(Y,X).
pyramid(X,Y):- prey(Z,X), pyramid(Z,Y).

Queries


We can now query this database. For each of the queries listed below, what do you think the computer will return?

True or False Queries:
The following queries would return either True or False.

?-herbivore(butterfly).
?-herbivore(fox).
?-omnivore(goldfinch).
?-predator(fox,squirrel)
etc.

Other Queries:
The following queries would return a solution which could be either:

  • A unique value
  • A list of values
  • False if no solution can be found
?-animal(X)
?-herbivore(X).
?-predator(goldfinch,X).
?-pyramid(fox).
etc.

Your Task:


Use a range of queries, similar to the one above to interrogate the knowledge base and complete the food web provided below.

To run your queries you will need to use the online Prolog environment:
https://swish.swi-prolog.org/p/Food-Web-Prolog.pl

Here is the template for the food web for you to complete:
prolog-food-web

Did you like this challenge?

Click on a star to rate it!

Average rating 3.7 / 5. Vote count: 22

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: