Perl & Prolog
Part 1 of Perl Weekly Challenge 043 seemed like a natural fit for a logic programming approach. Still, this is a Perl challenge. What is the best approach then? Interestingly there is a Pure Perl Prolog interpreter AI::Prolog!
First off, the challenge:

There are 5 rings in the Olympic Logo as shown. They are color coded as in Blue, Black, Red, Yellow and Green. We have allocated some numbers to these rings as below:
Blue: 8
Yellow: 7
Green: 5
Red: 9
The Black ring is empty currently. You are given the numbers 1, 2, 3, 4 and 6. Write a script to place these numbers in the rings so that the sum of numbers in each ring is exactly 11.
What I Did
The Perl code here is really just a wrapper around a Prolog program. The Prolog code is in the __DATA__ section which is read in and passed to the AI::Prolog constructor. We then make a single query and Prolog deduces the correct solution!
At a very high level this is what the Prolog program does:
- member is a (recursively defined) function which determines if some variable X is a member of a list. member takes two arguments so in Prolog terminology it is said to have an arity of 2 and is referred to as member/2.
- colors/5 is a function which states that each of the variables Blue, Yellow, Green, etc must be found in the list we were given.
- Furthermore, we must satisfy the conditions that each ring must sum to 11. Each ring is given a one letter variable R, G, B, Y, and so forth.
- Prolog will deduce the values for Red, Green, Black, ... and that is what will be returned to our Perl code.
Sample Run
$ perl perl/ch-1.pl
Red: 2
Green: 4
Black: 6
Yellow: 1
Blue: 3
Note: the above values are for the question marks as read from left to right in the figure.
Part 2
The second part of Challenge 043 was to generate so called self-descriptive numbers.
The following code follows directly form the definition.
Sample Run
$ perl perl/ch-2.pl
Base 4: 1210
Base 4: 2020
Base 5: 21200
Base 7: 3211000
Base 8: 42101000
Notes
- For anyone interested in learning more on the subject, especially from a Perl perspective, the article Logic Programming with Perl and Prolog is a very nice introduction to going further with Prolog.
- There is also no shortage of books on Prolog. A particularly fun one is Adventure in Prolog which instructs the reader in Prolog via the development of a simple text based adventure game.
Comments for this post were locked by the author