Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Prolog: Rules


Rules are used to make conditional statements about the world.

For example, a rule can be something like below.
a.   Person ‘x’ is taller than person ‘y’, if person x’s height is more than person y’s height.
b.   A person is eligible to vote, if he is more than 18 years old
c.    Two persons are brothers, if they are male and their parents are same
d.   I will go for a trek, if there is no rain

How to define a rule?
A rule in prolog consist of a header and body.

Syntax
head :- body.

As you see above syntax, head and body are connected by symbol :-. :- is pronounced as if.

A rule ends with a ‘.’

Let’s implement the brothers rule
X and Y are said to be brothers, if they satisfy below conditions.
a.   X and Y are males
b.   X and Y has same parents

To implement this, first we need to know that both X and Y are males, next X and Y has same parents.

Step 1: Define male and femal facts.
male(krishna).
male(rama).
male(hari).

female(chamu).
female(sowmya).
female(sailaja).

As you see I defined 6 facts that represent Krishna, rama and hari are males and chamu, sowmya and sailaja are females.

Step 2: Define parents fact.

parents(krishna, devi, lakshman).
For example, above statement says parent of ‘krishna’ are devi and Lakshman. Where ‘devi’ is mother and ‘lakshman’ is father.

I defined below facts.
parents(krishna, devi, lakshman).
parents(rama, devi, lakshman).
parents(hari, sudha, jangayya).
parents(chamu, lakshmi, narayana).
parents(sowmya, harini, ramakrishna).
parents(sailaja, nhargavi, narayana).

Step 3: Define brothers relation like below.
brothers(Person1, Person2) :- male(Person1), male(Person2), parents(Person1, Mother, Father), parents(Person2, Mother, Father).

Above statement says, Person1 and Person2 are said to be brothers, if
a.   Person1 is male
b.   Person2 is male
c.    Person1 mother and father are same as Person2’s

I used Person1, person2, Mother, Father variable name to give more clarity, if you are comfortable with X, Y notation, you can use the same.

relations.pl
male(krishna).
male(rama).
male(hari).

female(chamu).
female(sowmya).
female(sailaja).

parents(krishna, devi, lakshman).
parents(rama, devi, lakshman).
parents(hari, sudha, jangayya).
parents(chamu, lakshmi, narayana).
parents(sowmya, harini, ramakrishna).
parents(sailaja, nhargavi, narayana).

brothers(Person1, Person2) :- male(Person1), male(Person2), parents(Person1, Mother, Father), parents(Person2, Mother, Father).

1 ?- consult(relations).
true.

2 ?- brothers(krishna, rama).
true.

3 ?- brothers(krishna, hari).
false.

4 ?- brothers(krishna, chamu).
false.




This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Prolog: Rules

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×