2
votes

I want to know how I would get something like this to work. It seems like a simple concept, but I'm very new to Prolog and I can't seem to figure out how I would do this correctly.

For example, here are two tables. Each animal, regardless of the category, has two facts.

Mammal:

tiger - striped, powerful

hippo - large, dangerous

elephant - large, gentle

Insect:

fly - black, winged

caterpillar - green, slow

snail - slimy, slow

How would I write all of these statements in Prolog code such that the fly and its characteristics will be categorized under insect and the hippo and its characteristics under mammal?

Then, what if I inserted a rule such as this?

guess(mammal, large) 

After consulting the code, I would write out this command:

possibleanimal(mammal, X) 

and the conclusion to that command would be:

X = hippo 
X = elephant 

since both the hippo and the elephant have the large characteristic.

Another example:

guess(insect, slow) 
guess(insect, green)

Command asked after consulting:

possibleanimal(insect, Y) 
Y= caterpillar 

We can omit the snail because even though it is slow, it is not green.

Please help me out in any way you can, thank you!

1

1 Answers

1
votes

The first example looks like transitivity, so try this:

% animal(Animal, Property)
animal(tiger, striped).
animal(tiger, powerful).
animal(hippo, large).
animal(hippo, dangerous).
animal(elephant, large).
animal(elephant, gentle).

% guess(Category, Property)
guess(mammal, large).

% possibleanimal(Category, Animal)
possibleanimal(C, A) :-
       guess(C, P),
   animal(A, P).

?- possibleanimal(mammal, X).
X = hippo ;
X = elephant

Now the tricky part is the second example, since we have multiple guess/2.

And I guess you would like them to simultaneously hold. So you need a kind of forall.

Forall can be defined in Prolog as follows:

% forall(Goal,Goal)
forall(A, B) :- \+ (A, \+ B).

See for example: http://www.swi-prolog.org/pldoc/man?predicate=forall%2F2

So you can try this:

% possible(Animal)
    possible(fly).
    possible(caterpillar).
    possible(snail).

    % animal(Animal, Property)
animal(fly, black).
animal(fly, winged).
animal(caterpillar, green).
animal(caterpillar, slow).
animal(snail, slimy).
animal(snail, slow).


% guess(Category, Property)
guess(insect, green).
guess(insect, slow).

% possibleanimal(Category, Animal)
    possibleanimal(C, A) :-
        possible(A),
        forall(guess(C,P), animal(A,P)).

?- possibleanimal(insect,X).
X = caterpillar ;
No

Hope this helps.

Bye