Reputation: 373
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
Reputation: 40768
Such questions are very common among beginners. The key insight is that you want to describe a relation between 3 things:
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 Head
← Body
.
We can therefore read it as Body
→ Head
, 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