Saturday, 5 October 2013

Prolog

Why?

I got bored one night and decided to look back at some of the things that I once upon a time found cool.  One of those things was Prolog, Ok so it's an old technology but I can see where it is possibly the origin of many pattern matching languages like xslt.

Overview

So I flung together a simple family tree:



                Tom    Ada           Sylvia  Ron       Philip  Vera
                |       |             |       |          |       |
                +-------+             +-------+          +-------+
                    |                     |                  |
                +-------+            +----------+        +-------+
                |       |            |    |     |        |       |
     Derek    Trudy  Andrew      Stephen Carol  Susan  Alison   Susan
       |         |                  |                    |
       +---------+                  +--------------------+
            |                                  |
       +---------+                     +--------------+
       |         |                     |              |
     Faye       Lisa                Richard         Eleanor
                 |                     |
                 +---------------------+
                            |
                          Alaya
I then created some facts like this (note the facts are currently incomplete, got lazy).
male('Richard').
male('Stephen').
male('Derek').
male('Ronald').
male('Philip').
male('Andrew').
male('Tom').
female('Alaya').
female('Lisa').
female('Alison').
female('Trudy').
female('Vera').
female('Faye').
female('Sylvia').
female('Eleanor').
parent('Stephen', 'Eleanor').
parent('Stephen', 'Richard').
parent('Ronald','Stephen').
parent('Sylvia','Stephen').
parent('Philip','Alison').
parent('Richard','Alaya').
parent('Lisa','Alaya').
parent('Vera','Alison').
parent('Tom','Trudy').
parent('Eida','Trudy').
parent('Derek', 'Lisa').
parent('Derek', 'Faye').
parent('Alison', 'Eleanor').
parent('Alison', 'Richard').
parent('Trudy', 'Lisa').
parent('Trudy', 'Faye').
parent('Tom', 'Andrew').
Then once the facts are in I came up with some interesting queries on it.
father(X,Y) :- parent(X,Y), male(X).
mother(X,Y) :- parent(X,Y), female(X).
grandparent(X,Y) :- parent(X,Z), parent(Z,Y).
uncle(X,Y) :- parent(P,Y), parent(Z,P), parent(Z,X), P \= X,male(X).
Just to refresh my memory on how prolog and declarative languages generally work, I enjoyed this little trip down memory lane so may post some more musings at a later date.