N.W.
N.W.

Reputation: 373

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.

Upvotes: 0

Views: 219

Answers (1)

mat
mat

Reputation: 40768

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, i.e., 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_friend_colour(Person, Friend, FriendColor).
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!

Upvotes: 2

Related Questions