Prolog and Logic Programming

hasFlavor(F) :- instock(F).
instock(chocolate).

This is the first Prolog program I’ve written. Doesn’t look too impressive, does it? These two lines of code tell me that if a flavor is in stock, then we have a flavor. Then it states that the “chocolate” flavor is in stock, which therefore means that hasFlavor(chocolate) is true. If I were to query the program, saying

?- hasFlavor(chocolate)

it would print out Yes.

I wrote another prolog program using ASP (Answer Set Programming) that represents a family.

sibling(X,Y) :- parent(Z,X), parent(Z,Y).
mother(X,Y) :- parent(X,Y), female(X).
spouse(X,Y) :- parent(X,Z), parent(Y,Z).
female(kimberly). female(katherine). female(joanne). male(david).
parent(joanne, kimberly). parent(joanne, katherine).
parent(david, kimberly). parent(david, katherine).

This program prints out: 

parent(david,katherine) parent(david,kimberly) parent(joanne,katherine) parent(joanne,kimberly) male(david) female(joanne) female(katherine) female(kimberly) spouse(david,david) spouse(joanne,david) spouse(david,joanne) spouse(joanne,joanne) mother(joanne,katherine) mother(joanne,kimberly) sibling(katherine,katherine) sibling(kimberly,katherine) sibling(katherine,kimberly) sibling(kimberly,kimberly) 
True

Unlike other types of programming, in logic programming everything happens at once. There is no way to tell a program to perform steps in order, like you would in Java. How this works is that when it reaches statements like hasFlavor(F) :- instock(F), it searches for all terms that can substituted in for the argument (i.e. instock(chocolate)) and puts them in. In this way, the code is not read in a linear fashion, but rather “all at once”.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s