More Perl & Prolog

I had previously used AI::Prolog to create a hybrid Perl/Prolog solution to a Perl Weekly Challenge. This was not quite so arbitrary as it may have seemed! In fact, Prolog, Symbolic AI, and NLP are subjects taking up a good deal of my mental energy these days. So much so that there has been a discontinuity in my PWC submissions lasting the past several weeks! With the most recent weekly challenge there is once again a new opportunity to use AI::Prolog and hopefully get back into the swing of things as far as contributing solutions every week!

Part 1

Given an array @L of integers. Write a script to find all unique triplets such that a + b + c is same as the given target T. Also make sure a <= b <= c.

Sample Run

$ perl perl/
X: -10
Y: 2
Z: 8


I re-used member/2 from the previous AI::Prolog solution. Other than that I think the elegance of Prolog is apparent here: we require membership in the list, define the numerical conditions, and Prolog proceeds from there!

I also experimented with modifying the Prolog code via string substitution. It works fine here but other than small bits of code like this I suspect it would be too clunky to be a sustainable pattern.

Part 2

Write a script to display all Colorful Numbers with three digits.

Sample Run

$ perl perl/
100: not a colorful number
101: not a colorful number
102: not a colorful number
103: not a colorful number
423: colorful number
424: not a colorful number
425: colorful number
426: colorful number
427: colorful number
428: not a colorful number
429: colorful number
430: not a colorful number
431: not a colorful number
432: colorful number
433: not a colorful number
434: not a colorful number
435: colorful number
436: colorful number
437: colorful number
438: colorful number
439: colorful number
996: not a colorful number
997: not a colorful number
998: not a colorful number
999: not a colorful number


Ok. Admittedly Part 2 is not quite as natural a fit to a logic programming approach as Part 1. The uniqueness checks could have been written differently, for sure, but simply checking whether the numerical conditions hold is straightforward in any language. I do think that Part 2 shows a nice division of labor between the Perl and the Prolog parts, however. Perl can make quick work of looping over all the candidate numbers and splitting them into individual digits. The individual digits are then passed to Prolog for checking.

Comments for this post were locked by the author