简体   繁体   中英

How to make predicate for simple Prolog database

I have this database, which tells prolog who is who's friend and what that friends favourite colour is:

*/ has_friend(name, their friend)
has_friend(lisa, mary).
has_friend(john, peter).
has_friend(carl, erin).

*/ has_favourite_colour(their friend, colour)
has_favourite_colour(mary, red).
has_favourite_colour(peter, blue).
has_favourite_colour(erin, green).

What I want to do now is create a predicate "info/1" which uses the name as argument and then tells me who their friend is and what their favourite colour is. How do I do this? I basically suck at prolog and I've read 3 books and all sorts of tutorials but I can't figure it out.

Such questions are very common among beginners. The key insight is that you want to describe a relation between 3 things:

  1. a person
  2. their friend
  3. the friend's (I assume) favourite colour.

Consequently, it will be natural to use three arguments (not one) for such a relation.

A good predicate name helps to write down the definition in a straight-forward way:

person_friend_colour(Person, Friend, FriendColour) :-
        has_friend(Person, Friend),
        has_favourite_colour(Friend, FriendColour).

It is written here as a typical Prolog rule, ie, of the form HeadBody .

We can therefore read it as BodyHead , which may be a bit easier: If Friend is a friend of Person , and FriendColour is that friend's favourite colour, then it is the case that person_friend_colour/3 holds for these three entities.

Example query:


Person = lisa,
Friend = mary,
FriendColor = red ;
Person = john,
Friend = peter,
FriendColor = blue ;
Person = carl,
Friend = erin,
FriendColor = green.

This shows all solutions there are.

To obtain natural formulations of your relations, use an adequate number of arguments!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM